package go_36
import (
"errors"
"fmt"
"testing"
)
type Printer func(contents string) (n int, err error)
func printToStd(contents string) (bytesNum int, err error) {
return fmt.Println(contents)
}
func TestDemo26(t *testing.T) {
var p Printer
p = printToStd
a, e := p("something123")
fmt.Println(a, e)
}
type operate func(x, y int) int
// 方案 1
func calculate(x int, y int, op operate) (int, error) {
if op == nil {
return 0, errors.New("invalid operation")
}
return op(x, y), nil
}
// 方案 2
type calculateFunc func(x int, y int) (int, error)
func genCalculator(op operate) calculateFunc {
return func(x int, y int) (int, error) {
if op == nil {
return 0, errors.New("invalid operation")
}
return op(x, y), nil
}
}
func TestDemo27(t *testing.T) {
// 方案 1
x, y := 12, 23
op := func(x, y int) int{
return x * y
}
result, err := calculate(x, y, op)
fmt.Println(result, err)
result, err = calculate(x, y, nil)
fmt.Println(result, err)
// 方案 2
x, y = 56, 78
add := genCalculator(op)
result, err = add(x, y)
fmt.Println(result, err)
}
func modifyArray(a [3]string) [3]string {
a[1] = "x"
return a
}
func modifySlice(a []string) []string {
a[1] = "slice"
return a
}
func modifyComplexArray(a [3][]string) [3][]string {
a[1][1] = "slice"
a[2] = []string{"new", "array", "q"}
return a
}
func TestDemo28(t *testing.T) {
// 示例 1,修改数组,原始数组不变
array1 := [3]string{"a", "b", "c"}
fmt.Println(array1)
array2 := modifyArray(array1)
fmt.Println(array2)
fmt.Println(array1)
// 示例 2,修改切片,原始切片变化
slice1 := []string{"x", "y", "z"}
fmt.Println(slice1)
slice2 := modifySlice(slice1)
fmt.Println(slice2)
fmt.Println(slice1)
// 示例 3,修改数组时,原始数组不变;修改数组中切片,原始切片变化
complexArray1 := [3][]string {
[]string{"d", "e", "f"},
[]string{"g", "h", "i"},
[]string{"j", "k", "l"},
}
fmt.Println(complexArray1)
complexArray2 := modifyComplexArray(complexArray1)
fmt.Println(complexArray2)
fmt.Println(complexArray1)
}
评论