【问题标题】:How to change value of empty interface that pass as struct reference in golang?如何更改在golang中作为结构引用传递的空接口的值?
【发布时间】:2020-02-10 02:42:05
【问题描述】:

我有许多结构作为指针传递给一个名为 AutoFilled 的函数。每个结构都不同。但有些字段是相同的,例如“creator”、“createon”、“edition”.., 有没有办法改变 AutoFilled 函数中的公共字段?

package main

import (
    "fmt"
    "time"
)

type User struct {
    ID string
    Creator string
    CreateOn time.Time
    Edition int
    Name string
    Password string
}

type Book struct {
    ID string
    Creator string
    CreateOn time.Time
    Edition int
    Name string
    ISBN string

}

func AutoFilled(v interface{}) {
    // Add Creator
    // Add CreateOn
    // Add Edition (Version) [new is zero, edit increase 1]
}

func main() {
    user := User{}
    book := Book{}

    AutoFilled(&user)
    AutoFilled(&book)

    fmt.Println(user)
    fmt.Println(book)

    fmt.Println("Thanks, playground")
}

【问题讨论】:

    标签: pointers go struct interface


    【解决方案1】:

    看起来您只需要在其他结构中嵌入一个 Common 结构(有时称为 mixin)。

    type Common struct {
        ID string
        Creator string
        CreateOn time.Time
        Edition int
    }
    type User struct {
        Common
        Name string
        Password string
    }
    
    type Book struct {
        Common
        Name string
        ISBN string
    }
    

    另外我会让AutoFilled 函数成为Common 上的一个方法。 (使用接口会失去类型安全性。)

    func (c *Common)Autofill() {
        // set fields on Common struct
    }
    
    func main() {
            user := &User{}
            user.Autofill()
    
    

    【讨论】:

      【解决方案2】:

      @AJR 提供了一个非常好的选择。这是另一种方法。

      对于每个结构(BookUser),创建一个名为 New<StructName 的方法。以Book为例

      func NewBook() *Book {
          return &Book {
              //you can fill in default values here for common construct
          }
      } 
      

      您可以通过创建Common 结构进一步扩展此模式,并在创建时将该对象传递给NewBook,即

      func NewBook(c Common) *Book {
          return &Book {
              Common: c
              //other fields here if needed
          }
      }
      

      现在在您的主代码中,您将执行此操作

      func main() {
          c := NewCommon() //this method can create common object with default values or can take in values and create common object with those
          book := NewBook(c)
          //now you don't need autofill method
      
          fmt.Println("Thanks, playground")
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-29
        • 2020-01-30
        • 2016-10-11
        • 2018-09-07
        • 2020-03-02
        • 2021-12-20
        • 2013-07-22
        • 2021-09-25
        • 2020-03-31
        相关资源
        最近更新 更多