将struct字段参数传递给函数

时间:2013-12-26 17:37:37

标签: go

我有一个Message结构,以及一个创建新Message并对其执行某些操作的函数。

type Message struct { 
    To string
    From string
    Body string
}

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

我想把结构中的参数传递给函数,有点像这样(显然在语法上不正确,但你得到了要点)。

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

问题是,struct参数本身没有类型,因此无法直接将它们提供给函数。我可以给函数一个map,并从中获取参数,但我想尽可能简单地使用message函数,避免这样的事情:

Message(Message{/*params*/})

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

3 个答案:

答案 0 :(得分:1)

你到底想要完成什么?为什么struct参数本身没有类型。这有什么问题?

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}

答案 1 :(得分:0)

直接传递消息:

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",
})

虽然没有更多信息很难知道最好的方法。

答案 2 :(得分:-1)

我想你想要这样,但它在Golang中不是有效的风格。 的

消息(到: '雷',来自: '杰克')

相关问题