我是圍棋的新手,最近我正在遵循A Tour of Go的指導。我正在閱讀關于介面的章節,我對這個概念感到非常困惑。
代碼如下
package main
import "fmt"
func main() {
testTypeAssertion()
}
func testTypeAssertion() string {
var i interface{}="hello"
fmt.Printf("type of i is %T",i)
return i
// return "hello"
}
這種情況下會報錯
# example
./prog.go:12:2: cannot use i (type interface {}) as type string in return argument: need type assertion
但是如果我評論return i和取消評論return "hello",它就像這樣
type of i is string
那么為什么我們在這里需要一個型別斷言呢?具體是什么型別的i?
我相信這個問題與cannot use type interface {} as type person in assignment: need type assertion不同。因為在那個問題中,發帖人試圖將一個空的介面值分配給一個具有具體自定義型別的變數person。在我的問題中,我試圖弄清楚為什么持有具體string值的介面不能是回傳值型別為完全的函式的回傳值string。
Thanks to mkopriva's answer in the comment section and bugstop's answer. I will accept that it's caused by the different usage of static type and dynamic type. By the way, Reality's answer is very interesting and really helped me to understand the whole concept!
uj5u.com熱心網友回復:
將介面想象成一個包含型別和值的小盒子。該框具有映射到框中值的方法的方法。
該陳述句fmt.Printf("type of i is %T",i)列印框中的型別,而不是框本身的型別。需要反射包詭計來列印i. 但這超出了這個問題的范圍。
該陳述句return i無法編譯,因為interface{}它不是string. 該框包含一個字串,但該框不是string.
我們可以使用型別斷言:開箱即用地獲取值return i.(string)。i如果不包含字串,則此陳述句會發生恐慌。
uj5u.com熱心網友回復:
i它是一個動態型別的介面值string。
閱讀以下內容可能很有用:
- 如何確定 interface{} 值的“真實”型別?
- Go 中的介面
uj5u.com熱心網友回復:
該變數i的型別為interface{},其值為字串“hello”。介面只是一個方法集,由于 interface{}沒有指定方法,所有型別都滿足它。因此,作業i="hello"有效。
但是,您不能回傳需要interface{}a的地方string,因為string它與 a 的型別不同interface{}。你可以回傳一個stringwhere aninterface{}是必需的,因為一個字串實作了interface{}.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/424126.html
標籤:go
