簡體   English   中英

在Go中使用類似的指針結構來分配結構

[英]Assigning a struct using similar struct of pointers in Go

我有兩個相似的結構,我想將一個分配給另一個。 第一個“設備”是用於匹配數據庫的結構。 第二個“ 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中是否存在該字段。 更多信息: 在Go中進行封送處理時,如何識別無效值和未指定的字段?

因此,目前我創建了一個帶有許多“ 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
}

希望您能理解。

這個問題類似於使用另一個結構分配結構,但是由於指針=>非指針結構而有所不同

我不確定是否能正確理解您的問題,但不會像這樣:

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結構,而無需包含指針的其他“副本”。

您可以在此處嘗試此代碼。

編輯

我在下面所做的工作有效,但沒有達到我的預期。 實際上,我的第一個代碼是檢查空字段和未指定字段之間差異的唯一解決方案。

這是差異的演示: https : //play.golang.org/p/3tU6paM9Do


拳頭感謝大家的幫助,尤其是@Mihailo。

我最終要做的是讓我的模型結構沒有指針,即:

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

並且我使用了具有模型結構指針的JSON helper結構,即

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
}

高溫超導

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM