gpt4 book ai didi

Golang 报错我不是类型

转载 作者:IT王子 更新时间:2023-10-29 02:25:31 25 4
gpt4 key购买 nike

我有一个简单的函数,它接受一个变量获取其类型并将其处理到一个开关中,但我得到一个错误:

我不是一个类型

我的代码是这样的:

var whatAmI = func(i, interface{}) { // error is here
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool!")
case int:
fmt.Println("I'm an int!")
default:
fmt.Println("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")

我是不是误会了什么?

最佳答案

从函数签名中删除逗号,它将起作用。试一试 here .

package main

import (
"fmt"
)

func main() {
var whatAmI = func(i interface{}) { // error is here
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool!")
case int:
fmt.Println("I'm an int!")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")

}

此外,您错误地格式化了 default case print 语句,因此我更改了它以符合您的预期行为。

关于Golang 报错我不是类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46840691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com