我正在浏览Go游戏,我对指针和界面感到困惑.为什么这个Go代码没有编译?
package main
type Interface interface {}
type Struct struct {}
func main() {
var ps *Struct
var pi *Interface
pi = ps
_, _ = pi, ps
}
Run Code Online (Sandbox Code Playgroud)
即如果Struct是Interface,为什么不是*Struct一个*Interface?
我得到的错误信息是:
prog.go:10: cannot use ps (type *Struct) as type *Interface in assignment:
*Interface is pointer to interface, not interface
Run Code Online (Sandbox Code Playgroud) 我是接口的新手,并试图通过github做SOAP请求
我不明白的意思
Msg interface{}
Run Code Online (Sandbox Code Playgroud)
在这段代码中:
type Envelope struct {
Body `xml:"soap:"`
}
type Body struct {
Msg interface{}
}
Run Code Online (Sandbox Code Playgroud)
我观察到相同的语法
fmt.Println
Run Code Online (Sandbox Code Playgroud)
但不明白所取得的成就
interface{}
Run Code Online (Sandbox Code Playgroud) sort 包:
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
...
type reverse struct {
Interface
}
Run Code Online (Sandbox Code Playgroud)
Interfacestruct 中匿名接口的含义是什么reverse?
我有一个错误对象,当在控制台上打印给我 Token is expired
如何将其与特定错误值进行比较.我尝试了这个,但没有奏效.
if err == errors.New("Token is expired") {
log.Printf("Unauthorised: %s\n", err)
}
Run Code Online (Sandbox Code Playgroud) 在Golang中,我们使用带接收器方法的结构.一切都很完美到这里.
但是,我不确定接口是什么.我们在结构中定义方法,如果我们想在结构上实现一个方法,我们再次在另一个结构下编写它.
这意味着接口似乎只是方法定义,只占用了页面上额外不需要的空间.
有没有例子解释我为什么需要一个界面?
我正在阅读Go Go Programming Languagex.(T)中的类型断言并且不理解它们.
我知道有不同的场景:
这是我不明白的:
我也搜索了这个话题,仍然不明白.
我还是Go的新手,我很惊讶无法使用嵌入式接口的子类型.这是一个小例子来解释我的意思:
func test(sl bufio.ReadWriter){
// cannot use sl(type bufio.ReadWriter) as type bufio.Reader in function argument
readStuff(sl)
[...]
writeStuff(sl) // same kind of error
}
func readStuff(sl bufio.Reader){
[...]
}
Run Code Online (Sandbox Code Playgroud)
由于每个接口都具有相同的内存布局,而ReadWriter是Reader和Writer,因此我希望此代码能够正常工作.我确实尝试将接口类型转换为:
readStuff(sl.(buffio.Reader))
Run Code Online (Sandbox Code Playgroud)
但它也不起作用.所以我有两个问题:
Go语言将接口类型作为功能,类似于C风格的接口.但是,Go的接口类型似乎没有被强制执行 - 它们只是定义协议而不实际应用于类型.由于它们没有强制执行,使用接口仍然是个好主意吗?
我是一名Java程序员,学习在Go中编程.到目前为止,我非常喜欢这种语言.比Java更多.
但有一件事我有点困惑.Java具有接口,因为类只能从一个类继承.由于Go允许多重继承,接口的重点是什么?