[英]Why does returning a concrete type not satisfy a Interface requiring a Interface return
[英]Why can't I use an empty interface that holds a concrete type of string as a return value in a function declared to return string?
我是go的新人,最近正在跟隨Go的A Tour的指導。 我正在閱讀關於界面的章節,我真的對這個概念感到困惑。
代碼如下
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
值的接口不能是 function 的返回值,其返回值類型恰好是string
。
感謝mkopriva在評論區的回答和bugstop的回答。 我會接受這是由static 類型和動態類型的不同用法引起的。 順便說一句, Reality的回答非常有趣,確實幫助我理解了整個概念!
將接口想象成一個包含類型和值的小盒子。 該框的方法是 map 到框中值的方法。
語句fmt.Printf("type of i is %T",i)
打印框中的類型,而不是框本身的類型。 需要反射 package 技巧來打印i
的類型。 但這不在這個問題的 scope 范圍內。
語句return i
無法編譯,因為interface{}
不是string
。 該框包含一個字符串,但該框不是一個string
。
我們可以使用類型斷言直接獲取值: return i.(string)
。 如果i
不包含字符串,則此語句會發生恐慌。
變量i
的類型是interface{}
,它的值是字符串“hello”。 接口只是一個方法集,並且由於interface{}
沒有指定方法,所以所有類型都滿足它。 因此,賦值i="hello"
有效。
但是,您不能在需要string
的地方返回interface{}
,因為string
與interface{}
的類型不同。 您可能已經在需要interface{}
的地方返回了一個string
,因為字符串實現了interface{}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.