[英]Passing Struct array elements as parameters to a function in Go language
[英]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.