go 断言 官方教程翻译

原文

Type assertions

type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

Note the similarity between this syntax and that of reading from a map.

翻译

类型断言

类型断言提供对接口值的基础具体值的访问。

t := i.(T)

该语句断言接口值i拥有具体类型T,并将基础T值分配给变量t。

如果我不持有T,则该语句将引发恐慌。

为了测试接口值是否具有特定类型,类型断言可以返回两个值:基础值和报告断言是否成功的布尔值。

t, ok := i.(T)

如果我持有T,则t将是基础值,而ok将为真。

如果不是,则ok将为false,t将为T类型的零值,并且不会发生恐慌。

请注意,此语法与map读取语法之间的相似性。

示例

package main

import "fmt"

func main() {
	var i interface{} = "hello"

	s := i.(string)
	fmt.Println(s)

	s, ok := i.(string)
	fmt.Println(s, ok)

	f, ok := i.(float64)
	fmt.Println(f, ok)

	f = i.(float64) // panic
	fmt.Println(f)
}
发布了32 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/takujo/article/details/103977426