gpt4 book ai didi

go - 在动态结构函数 Golang 中修改结构值

转载 作者:数据小太阳 更新时间:2023-10-29 03:43:49 25 4
gpt4 key购买 nike

我有带setter函数的结构

package main

type Person struct {
Name string
Age int
}

func (p *Person) SetName(name string) {
p.Name = name
}

func SomeMethod(human interface{}){
// I call the setter function here, but doesn't seems exist
human.SetName("Johnson")
}

func main(){
p := Person{Name : "Musk"}
SomeMethod(&p)
}

报错如下:

human.SetName undefined (type interface {} is interface with no methods)

似乎 func SetName 没有包含在 SomeMethod

为什么会这样?任何答案将不胜感激!

最佳答案

使用setName创建接口(interface)并在Person结构上实现它然后调用SomeMethod设置Person的值>

package main

import "fmt"

type Person struct {
Name string
Age int
}

type Human interface{
SetName(name string)
}

func (p *Person) SetName(name string) {
p.Name = name
}

func SomeMethod(human Human){
human.SetName("Johnson")
}

func main(){
p := &Person{Name : "Musk"}
SomeMethod(p)
fmt.Println(p)
}

Go playground

要使用 getter 方法为任何通过 Human 接口(interface)传递的结构获取名称,请在 Human 接口(interface)上实现 getter 属性

package main

import (
"fmt"
)

type Person struct {
Name string
Age int
}

type Person2 struct{
Name string
Age int
}

type Human interface{
getName() string
}

func (p *Person2) getName() string{
return p.Name
}

func (p *Person) getName() string{
return p.Name
}

func SomeMethod(human Human){
fmt.Println(human.getName())
}

func main(){
p := &Person{Name : "Musk"}
SomeMethod(p)
p2 := &Person2{Name: "Joe"}
SomeMethod(p2)
}

Go playground

关于go - 在动态结构函数 Golang 中修改结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49579756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com