github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/cmp/cmp_test.go (about) 1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cmp_test 6 7 import ( 8 "github.com/shogo82148/std/cmp" 9 "github.com/shogo82148/std/fmt" 10 "github.com/shogo82148/std/slices" 11 ) 12 13 func ExampleOr() { 14 // Suppose we have some user input 15 // that may or may not be an empty string 16 userInput1 := "" 17 userInput2 := "some text" 18 19 fmt.Println(cmp.Or(userInput1, "default")) 20 fmt.Println(cmp.Or(userInput2, "default")) 21 fmt.Println(cmp.Or(userInput1, userInput2, "default")) 22 // Output: 23 // default 24 // some text 25 // some text 26 } 27 28 func ExampleOr_sort() { 29 type Order struct { 30 Product string 31 Customer string 32 Price float64 33 } 34 orders := []Order{ 35 {"foo", "alice", 1.00}, 36 {"bar", "bob", 3.00}, 37 {"baz", "carol", 4.00}, 38 {"foo", "alice", 2.00}, 39 {"bar", "carol", 1.00}, 40 {"foo", "bob", 4.00}, 41 } 42 // Sort by customer first, product second, and last by higher price 43 slices.SortFunc(orders, func(a, b Order) int { 44 return cmp.Or( 45 cmp.Compare(a.Customer, b.Customer), 46 cmp.Compare(a.Product, b.Product), 47 cmp.Compare(b.Price, a.Price), 48 ) 49 }) 50 for _, order := range orders { 51 fmt.Printf("%s %s %.2f\n", order.Product, order.Customer, order.Price) 52 } 53 54 // Output: 55 // foo alice 2.00 56 // foo alice 1.00 57 // bar bob 3.00 58 // foo bob 4.00 59 // bar carol 1.00 60 // baz carol 4.00 61 }