【问题标题】:Modify struct value inside dynamic struct function Golang修改动态结构函数Golang中的结构值
【发布时间】:2018-03-30 18:46:23
【问题描述】:

我有带有 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 方法)

似乎 func SetName 不包含在 SomeMethod

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

【问题讨论】:

  • 空接口interface{}没有方法。您使用参数类型 interface{} 而不是 '*Person` 是否有原因?
  • 因为我想让它成为接受任何结构类型的通用/动态函数@CeriseLimón
  • @Angger 你需要在setter上实现接口
  • @Angger 更新问题以说明您的实际目标。
  • 不可能完全通用。您不能在没有 SetName 方法的情况下调用 SetName。如果要在函数中调用SetName,则必须指定参数至少是一个包含SetName且签名相同的接口。

标签: go struct interface


【解决方案1】:

setName创建一个接口并在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 接口上实现 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

【讨论】:

  • 我也可以将“SetName”功能设为动态吗?因为我希望自动通过 SomeMethod 的所有内容都可以使用 SetName 方法。 @Himanshu
  • @Angger 没有自动调用方法的方法。您必须在Human 接口封装的给定对象上调用该方法。
  • 但是 Human 内部的 SetName 方法只属于 Person。我想让这个 SetName 方法也适用于传递给 SomeMethod 的任何结构? @Himanshu
  • @Angger 它将应用于您在接口内传递的任何结构。使用 getter 检查更新的代码以获取您传递的名称。
猜你喜欢
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2017-03-04
  • 1970-01-01
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多