相关疑难解决方法(0)

Go - 如何处理结构类型之间的公共字段

如果我有两种类型:

type A struct {
      X int
      Y int
}

type B struct {
      X int
      Y int
      Z int 
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现以下,而不需要两个方法,因为两者都访问相同名称的字段并返回它们的总和?

func (a *A) Sum() int {
     return a.X + a.Y
}

func (b *B) Sum() int {
     return b.X + b.Y
}
Run Code Online (Sandbox Code Playgroud)

当然,有X和Y方法,我可以定义一个包含这两种方法的接口.字段有模拟吗?

struct types go

6
推荐指数
1
解决办法
321
查看次数

如何为在golang中具有一个公共字段的不同结构添加一种方法

我正在为我的应用程序使用 beego/orm。这里我有 2 个模型

type ModelA struct {
    Guid string `orm:"pk"`
    FiledA string
}

type ModelB struct {
    Guid string `orm:"pk"`
    FiledB string
}
Run Code Online (Sandbox Code Playgroud)

我需要Save()为每个结构添加一个方法。通常,我可以创建一个Base结构并将其混合到ModelAand 中ModelB,但是 orm 不起作用。

有没有更好的解决办法?

编辑1:Save()在此处提供代码以使问题更清楚

func (this *ModelA) Save() error {
    o := orm.NewOrm()
    guid := guidlib.Generate()
    this.Guid = guid
    _, err := o.Insert(this)
    return err
}

func (this *ModelB) Save() error {
    o := orm.NewOrm()
    guid := guidlib.Generate()
    this.Guid = guid
    _, err := …
Run Code Online (Sandbox Code Playgroud)

go beego

3
推荐指数
1
解决办法
3551
查看次数

在多个结构体中重用 Go 中的函数

:) 我知道这看起来像是一个重复的问题,但我发现的每个问题都没有真正准确地回答我想要做的事情。我是 Go 新手,所以我可能会遗漏一些小东西。

我正在尝试做与此类似的事情,但对我来说不同的是我需要一个访问多个属性而不是单个属性的函数。我不是在寻找接口。我想要一次使用这个函数代码,因为它对于每个不同的结构都是相同的。

我是 Go 新手,但我认为该函数需要接受/使用结构指针,因为我需要它们更新。

例子:

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 …
Run Code Online (Sandbox Code Playgroud)

go

2
推荐指数
1
解决办法
201
查看次数

标签 统计

go ×3

beego ×1

struct ×1

types ×1