我可以像这样将int类型转换为float64类型:
var a int = 10
var b float64 = float64(a)
关于类型断言,Effective Go声明:“类型必须是接口持有的具体类型,或者是值可以转换为的第二个接口类型。”
考虑到这一点,为什么以下操作会失败:
func foo(a interface{}) {
fmt.Println(a.(float64))
}
func main() {
var a int = 10
foo(a)
}
这会导致panic: interface conversion: interface is int, not float64
。
请注意,Go Spec说:
‘对于接口类型的表达式x和类型T,主表达式
x.(T)
断言x不是nil,并且存储在x中的值是T类型。
这确实与有效的Go声明相矛盾,但似乎更符合我所看到的。
发布于 2013-05-30 21:28:43
Effective Go中的This sentence似乎确实令人困惑。看起来作者当时正在考虑结构。
The chapter on assertions in the specification要清晰得多:
表示接口类型的表达式x和类型T,它是主表达式
x.( T )断言x不是nil,并且存储在x中的值是T类型。符号x(T)称为类型断言。
更准确地说,如果T不是接口类型,x。( T )断言x的动态类型与类型T相同。在这种情况下,T必须实现x的(接口)类型;否则类型断言是无效的,因为x不可能存储类型T的值。如果T是接口类型,x。(T)断言x的动态类型实现接口T。
you can convert your int to a float (反之亦然)这一事实并不意味着您可以断言它们是同一类型。
发布于 2013-05-31 05:42:01
类型必须是接口持有的具体类型,或者是值可以转换为的第二个接口类型
这基本上解释了following
package main
import "fmt"
type Stringer interface {
String()
}
type Byter interface {
Bytes()
}
type Stringbyter interface {
Stringer
Byter
}
type Polymorphic float64
func (p *Polymorphic) String() {}
func (p *Polymorphic) Bytes() {}
func main() {
i := interface{}(new(Polymorphic))
if _, ok := i.(Stringer); ok {
fmt.Println("i can be asserted to Stringer")
}
if _, ok := i.(Byter); ok {
fmt.Println("i can be asserted to Byter")
}
if _, ok := i.(Stringbyter); ok {
fmt.Println("i can be asserted to Stringbyter")
}
if _, ok := i.(*Polymorphic); ok {
fmt.Println("i can be asserted to *Polymorphic")
}
if _, ok := i.(int); ok {
fmt.Println("i can be asserted to int") // Never runs
}
}
对int
的断言失败,因为它是一个具体的类型(与接口类型相反),而不是*Polymorphic
本身。
发布于 2014-05-31 02:29:36
只能将assert类型从接口类型转换为基础类型。在本例中为int
。然后使用从int
到float64
的类型转换
https://stackoverflow.com/questions/16837375
复制相似问题