簡體   English   中英

將結構字段參數傳遞給函數

[英]Passing struct field parameters to a function

我有一個Message結構,以及一個創建新Message並對其進行處理的函數。

type Message struct { 
    To string
    From string
    Body string
}

func Message() {
    newMessage := Message{Body: "test"}
    // do something with newMessage
}

我想將參數傳遞給struct到函數中,就像這樣(顯然在語法上不正確,但要領)。

func Message(/*params*/) {
    newMessage := Message{/*params*/}
    // do something with newMessage
}

問題是,結構參數本身沒有類型,因此無法將它們直接賦予函數。 我可能可以給函數一個映射,然后從那里獲取參數,但是我想繼續盡可能簡單地使用message函數,避免這樣的事情:

Message(Message{/*params*/})

var params map[string]string
// set parameters
Message(params)

您到底想完成什么? 為什么結構參數本身不具有類型。 這有什么問題?

package main

import "fmt"

type Message struct {
    To   string
    From string
    Body string
}

func NewMessage(to, from, body string) *Message {
    message := &Message{
        To:   to,
        From: from,
        Body: body,
    }
    // do something with message
    return message
}

func main() {
    message := NewMessage(
        "message to",
        "message from",
        "message body",
    )
    fmt.Println("Message: ", *message)
}

輸出:

Message:  {message to message from message body}

只需直接傳遞一條消息:

func Send(msg Message) {
    // do stuff with msg
}
Send(Message{"to","from","body"})

如果還有其他屬性需要初始化,可以這樣進行:

type Message struct {
    id int
    To, From, Body string
}

func (this *Message) init() {
    if this.id == 0 {
        this.id = 1 // generate an id here somehow
    }
}

func Send(msg Message) {
    msg.init()
    // do stuff with msg
}

Send(Message{
    To: "to",
    From: "from",
    Body: "body",
})

盡管沒有更多信息,很難知道最好的方法。

我想您想這樣,但是在Golang中這不是有效的樣式。

暫無
暫無

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

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