为未导出基础结构的所提供的接口Golang修改基础结构



我有一个场景,我必须写一个方法,在那里我修改传递的接口的底层结构,我已经意识到我可以传递一个指针到接口,然后使用指针来获得底层结构并操纵它,但从我学到的使用指针到接口几乎从不需要。有没有人能提出更好的方法来实现以下所需的功能?

package main
import (
"fmt"
)
type person struct {
name string
age  int
}
type iperson interface {
walk()
changeName(string) *person
}
func (p person) walk() {
fmt.Println("tip tap toe")
}
func (p person) changeName(name string) *person {
return &person{name: name, age: p.age}
}
func modifyStr(s *string) {
*s = "world"
}
func modifyStruct(p *person) {
*p = person{name: "john", age: 10}
}
func modifyInterface(i iperson) {
//i.walk()
p := i.(*person)
*p = person{name: "diff name", age: 111}
}
func modifyInterfaceWithUnexportedStruct(target interface{}) {
// We can do so by type assertion on pointer to interface but this is not recommended
// this works but is there any other way possible? i.e without having access to underlying struct but still manipulating it?
p := target.(*iperson)
*p = *(*p).changeName("some random name")
}
func main() {
//modifying a string in a function call
a := "hello"
modifyStr(&a)
fmt.Println(a)
//modify a struct in a function call
b := person{name: "sam", age: 2}
modifyStruct(&b)
fmt.Println(b)
//modify a interface in a function call using the underlying struct
c := person{name: "tom", age: 2}
modifyInterface(&c)
fmt.Println(c)
//modify a passed interface in a function call without using the underlying struct
d := iperson(person{name: "abc", age: 21})
fmt.Println(d)
modifyInterfaceWithUnexportedStruct(&d)
fmt.Println(d)
}

你的接口已经提供了一个changeName方法,但是它的实现没有改变接收person的名称,它返回一个新的person,与接收方和传递的名称相同的年龄。

接口的思想是与接口交互的代码不需要知道具体的实现。但是如果changeName返回一个*person,你已经强迫调用者知道实现细节。

为什么不像这样实现change Name呢?

func (p *person) changeName(n string) {
p.name = n
}

最新更新