:) 我知道这看起来像是一个重复的问题,但我找到的每个问题都没有确切地回答我想要做的事情.我是新来的,所以我可能错过了一些小东西.

我正在try 执行类似于this的操作,但对我来说,不同之处在于我需要一个可以访问多个属性的函数,而不是只访问一个属性.我不是在找界面.我希望这个函数代码只有一次,因为它对于每个不同的 struct 都是相同的.

我是新手,但我认为该函数需要接受/使用 struct 的指针,因为我需要更新它们.

示例:

type ModelA struct {
    choices  []string 
    cursor   int     
    selected string
    name     string   
}

type ModelB struct {
    choices  []string 
    cursor   int     
    selected string   
    year     int
}

func (m ModelA or ModelB) CommonFunction(originalString string, otherArguments ) string {
    originalString += question

    // Iterate over our choices
    for idx, choice := range m.choices {

        // Is the cursor pointing at this choice?
        cursor := " " // no cursor
        if m.cursor == idx {
            cursor = ">" // cursor!
        }

        // Is this choice selected?
        checked := " " // not selected
        if m.selected == choice {
            checked = "x" // selected!
        }

        // Render the row
        originalString += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)
    }

    originalString += "\nPress ctrl + q to quit.\n"
    return "\n" + originalString + "\n\n"
}

我不确定我想做什么是可能的,但我想从比我更像是Golang专家的人那里知道.

推荐答案

您可以执行struct embedding:)

https://go.dev/play/p/mEsvmtlHbPL

type inner struct {
    choices  []string
    cursor   int
    selected string
}

type ModelA struct {
    inner
    name string
}

type ModelB struct {
    inner
    year int
}

func (m inner) CommonFunction() string {
    // ...
    return "common"
}

func main() {
    modelAinstance := &ModelA{
        name: "hello",
    }
    modelAinstance.CommonFunction()

    modelBinstance := &ModelB{
        year: 2012,
    }
    modelBinstance.CommonFunction()
}

Go相关问答推荐

有没有更简单的方法在Go中编写这个逻辑?

使用恶意软件 scanner (ClamAV)时的Google云存储桶上传文件验证

SEARCH On Conflict Clause不考虑乐观锁定版本

如何防止程序B存档/删除围棋中程序A当前打开的文件?

go测试10m后如何避免超时

如何确定泛型类型在运行时是否可比较?

这是go语言gin提供的关于TypeEngine和RouterGroup的问题

无效操作:v > max(类型参数 T 与 > 不可比较)

hyperledger fabric - go:在 $PATH 中找不到可执行文件

Golang - POST 失败(NoSurf CSRF)

Go 中如何调用测试函数?

判断一个区域内的纬度/经度点

golang yaml 马歇尔网址

访问传递给可变参数函数的通用 struct 的特定字段

使用go doc命令查看示例函数?

如何在gin中获取参数值数组

在 connect-go 拦截器中修改响应体

Golang 泛型

测试包外文件时的 Golang 测试覆盖率

Go 语言的select语句