我是接口的新手,并试图通过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) 在Golang中,我们使用带接收器方法的结构.一切都很完美到这里.
但是,我不确定接口是什么.我们在结构中定义方法,如果我们想在结构上实现一个方法,我们再次在另一个结构下编写它.
这意味着接口似乎只是方法定义,只占用了页面上额外不需要的空间.
有没有例子解释我为什么需要一个界面?
我有带接口的代码:
package main
import (
"math"
"fmt"
)
type Circle struct {
x, y, r float64
}
type Rectangle struct {
x1, y1, x2, y2 float64
}
type Figure interface {
Area() float64
}
func (c *Circle) Area() float64 {
return math.Pi * c.r * c.r
}
func (r *Rectangle) Area() float64 {
return math.Abs(r.x2 - r.x1) * math.Abs(r.y2 - r.y1)
}
func main() {
figures := make([]Figure, 0)
figures = append(figures, &Circle{0, 0, 10})
figures = append(figures, &Rectangle{0, 0, …Run Code Online (Sandbox Code Playgroud) 这里只是一个简单的语言设计相关问题.在像Swift这样的语言中,为了使struct/class符合协议/接口,需要明确地将其声明为
struct Dog: Animal {
// implementation of Animal protocols here
}
Run Code Online (Sandbox Code Playgroud)
但是为什么在Go中,没有明确的方法来显示结构符合的接口?
这不仅仅是让事情不清楚,还是有任何其他原因呢?
Go语言将接口类型作为功能,类似于C风格的接口.但是,Go的接口类型似乎没有被强制执行 - 它们只是定义协议而不实际应用于类型.由于它们没有强制执行,使用接口仍然是个好主意吗?
我是一名Java程序员,学习在Go中编程.到目前为止,我非常喜欢这种语言.比Java更多.
但有一件事我有点困惑.Java具有接口,因为类只能从一个类继承.由于Go允许多重继承,接口的重点是什么?
我最近喜欢Go编程语言,到目前为止我发现它很精彩,但我真的很难理解接口.我已经阅读了很多关于它们的内容,但它们对我来说似乎仍然非常抽象.
我写了一些使用以下界面的代码:
package main
import (
"fmt"
"math"
)
type Circer interface {
Circ() float64
}
type Square struct {
side float64
}
type Circle struct {
diam, rad float64
}
func (s *Square) Circ() float64 {
return s.side * 4
}
func (c *Circle) Circ() float64 {
return c.diam * math.Pi
}
func (c *Circle) Area() float64 {
if c.rad == 0 {
var rad = c.diam / 2
return (rad*rad) * math.Pi
} else {
return (c.rad*c.rad) * …Run Code Online (Sandbox Code Playgroud) 我不明白为什么go开发人员选择了类似于func (t Type) MethodName()方法的语法.我无法消化这一事实,特别是在阅读本文并考虑到go是极简主义的事实之后.岂不更简单的语法像func Type.MethodName()或func Type::MethodName()已经足够与物体使用隐含参数像访问this或self.或者我错过了当前语法提供的任何优势?