下面这段代码输出什么? #
package main
import "fmt"
type T struct {
abc []int
xyz string
}
func foo(t T) {
t.abc[0] = 100
t.xyz= "good"
}
func main() {
var t = T{
abc: []int{1, 2, 3},
xyz:"hello",
}
foo(t)
fmt.Println(t.abc[0])
fmt.Println(t.xyz)
}
答: 100
hello
原因:调用 foo() 函数时虽然是传值,但 foo() 函数中,字段abc是切片为引用传递,而xyz是字符串为传值
下面代码输出什么? #
package main
import "fmt"
func main() {
isMatch := func(i int) bool {
switch(i) {
case 1:
case 2:
return true
}
return false
}
fmt.Println(isMatch(1))
fmt.Println(isMatch(2))
}
答: false
true
因为: switch 语句没有"break",但如果 case 完成程序会默认 break,可以在 case 语句后面加上关键字 fallthrough
2种解决办法:
1. isMatch := func(i int) bool {
switch(i) {
case 1:
fallthrough
case 2:
return true
}
return false
}
2. isMatch := func(i int) bool {
switch(i) {
case 1, 2:
return true
}
return false
}