在 Go 中使用类似的指针结构分配结构

Assigning a struct using similar struct of pointers in Go

我有两个相似的结构,我想将一个分配给另一个。 第一个"Equipment"是用来匹配数据库的结构。第二个 "JsonEquipment" 是解析 JSON 数据的辅助结构。

示例如下:

type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

type JsonEquipment struct {
    ID           *uint
    Category     *string
    Ip           *string
    Login        *string
    Password     *string
}

指针用于检查字段是否存在于 JSON 中。更多信息:

所以目前我创建了一个包含许多 "if" 的函数来检查并分配给设备,但我想知道是否有更好更清洁的解决方案。

func CreateEquipment(item JsonEquipment) (Equipment) {
    e := Equipment{}

    if item.ID != nil && !previousEquipment.Auto { // Is the field present & not automatic equipment
        e.ID = *item.ID
    }

    if item.Ip != nil { // Is the field present ?
        e.Ip = *item.Ip
    }

    if item.Login != nil { // Is the field present ?
        e.Login = *item.Login
    }

    [...]
    return e
}

希望你能把握思路。

This question is similar to but is different because of the pointers => non pointers struct

我不确定是否正确理解了你的问题,但这样的事情不会完成工作:

type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

func main(){
    // Grabing the equipment.
    equips := getEquipment()

    // Checking each equipment for its validity.
    for _, e := range equips {
        if (e.isValid()) {
            fmt.Println(e, "is OK!")
        } else {
            fmt.Println(e, "is NOT OK!")
        }
    }
}

// getEquipment fetches the json from the file.
func getEquipment() (e []Equipment) {
    raw, err := ioutil.ReadFile("./equipment.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    json.Unmarshal(raw, &e)

    return 
}

// isValid checks if the equipment has all the required fields.
func (e *Equipment) isValid() bool {
    if (e.Ip == "" || e.Login == "") { // You might add more validation rules
        return false
    }

    return true
}

它非常简单,但我不确定您还想在这里做什么。
这样你就有了一个 Equipment 结构,不需要另一个 "copy" 包含指针。

您可以试试这段代码 here

编辑

我在下面所做的工作有效,但没有达到我的预期。 实际上我的第一个代码是检查空字段和未指定字段之间差异的唯一解决方案。

以下是差异的演示: https://play.golang.org/p/3tU6paM9Do


非常感谢大家的帮助,尤其是@Mihailo。

我最终做的是让我的模型结构没有指针,即:

type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

我使用了一个 JSON 辅助结构,它有一个模型结构的指针,即

type JsonHelper struct {
    Equipments    []*Equipment
    [Add other structures here]
}

最后我使用 JsonHelper 结构解析了 JSON:

func ParseJSON(inputPath string) JsonHelper {
    // Read configuration file
    content, err := ioutil.ReadFile(inputPath)
    if err != nil {
        log.Println("Error:", err)
    }

    var input JsonHelper

    // Parse JSON from the configuration file
    err = json.Unmarshal(content, &input)
    if err != nil {
        log.Print("Error: ", err)
    }

    return input
}

HTH