golang面试-day50

下面这段代码输出什么?
type T struct {
    ls []int
}
func foo(t T) {
    t.ls[0] = 100
}
func main() {
    var t = T{
        ls: []int{1, 2, 3},
    }
    foo(t)
    fmt.Println(t.ls[0])
}
  • A. 1

  • B. 100

  • C. compilation error

参考答案及解析:B。调用 foo() 函数时虽然是传值,但 foo() 函数中,字段 ls 依旧可以看成是指向底层数组的指针。

2.下面代码输出什么?
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。Go 语言的 switch 语句虽然没有"break",但如果 case 完成程序会默认 break,可以在 case 语句后面加上关键字 fallthrough,这样就会接着走下一个 case 语句(不用匹配后续条件表达式)。或者,利用 case 可以匹配多个值的特性。

修复代码:

func main() {
    isMatch := func(i int) bool {
        switch(i) {
        case 1:
            fallthrough
        case 2:
            return true
        }
        return false
    }
    fmt.Println(isMatch(1))     // true
    fmt.Println(isMatch(2))     // true
    match := func(i int) bool {
        switch(i) {
        case 1,2:
            return true
        }
        return false
    }
    fmt.Println(match(1))       // true
    fmt.Println(match(2))       // true
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值