我正在努力学习Go,我在这里找到了一个很好的资源.
关于方法重载的示例如下:
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Employee struct {
Human
company string
}
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
func (e *Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone) //Yes you can split into 2 lines here.
}
func main() {
sam := Employee{Human{"Sam", …Run Code Online (Sandbox Code Playgroud) 我有以下几点:
type Base struct {
}
func(base *Base) Get() string {
return "base"
}
func(base *Base) GetName() string {
return base.Get()
}
Run Code Online (Sandbox Code Playgroud)
我想用新的 Get() 实现定义一个新类型,以便我可以使用新类型代替Base调用 GetName() 的位置,它调用新的 Get() 实现。如果我使用 Java,我将继承 Base 并覆盖 Get()。我应该如何在 Go 中实现这一目标?如果可能,我想避免破坏更改,因此不需要更改 Base 的现有使用者。
我第一次尝试这个看起来像..
type Sub struct {
Base
}
func(sub *Sub) Get() string {
return "Sub"
}
Run Code Online (Sandbox Code Playgroud)
..这不起作用。我的大脑还没有清楚地连接到围棋。
我对 golang 还很陌生,我正在为一项简单的任务而苦苦挣扎。
我在 golang 有以下课程
type struct A {
}
func (s *A) GetFirst() {
s.getSecond()
}
func (s *A) getSecond() {
// do something
}
Run Code Online (Sandbox Code Playgroud)
我想为它编写一些测试,但是我需要覆盖getSecond(). 我试图在我的测试文件中执行以下操作
type Ai interface {
getSecond()
}
type testA struct {
A
}
func (s *testA) getSecond() {
// do nothing
}
func TestA(t *testing.T) {
a := &A{}
t := &testA{A: a}
t.GetFirst()
}
Run Code Online (Sandbox Code Playgroud)
这里的想法是将 AgetSecond()方法公开给接口并通过使用嵌入来覆盖,但这似乎不起作用。测试仍然调用原始实现getSecond()而不是我的模拟实现。
一个解决方案当然是为 A 创建一个适当的接口,其中包含getFirst(),getSecond()然后在测试中创建一个结构,实现 wheregetFirst() …
我想知道在golang中做这样的事情是否可行 -
type MyStruct struct {
id int
}
func (ms *MyStruct) PrintHello() {
fmt.Printf("Hello from original method %v", ms.id)
}
func main() {
fmt.Println("Hello, playground")
m := MyStruct{}
m.PrintHello()
m.PrintHello = func() {fmt.Printf("Hello from newer method 2")}
}
Error: cannot assign to m.PrintHello
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/2oJQFFH4O5
很抱歉,如果这对Go程序员没有意义,我是Go的新手,想知道是否可以在Go中完成动态类型语言中可以完成的一些事情.谢谢!:-)
我试图在GO中实现这种多态性
type Discoverer interface {
Discover() string
}
type A struct {
}
func (obj A) GetTest() string {
return "im in A"
}
type B struct {
A
}
func (obj B) GetTest() string {
return "im in B"
}
func (obj A) Discover() string {
return obj.GetTest()
}
func main() {
a := A{}
b := B{}
fmt.Println(a.Discover())
fmt.Println(b.Discover())
}
Run Code Online (Sandbox Code Playgroud)
现在我进入输出
im in A
im in A
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是:可以在输出中看到
im in A
im in B
Run Code Online (Sandbox Code Playgroud)
没有"覆盖"发现B?
func (obj B) …Run Code Online (Sandbox Code Playgroud)