[英]Passing struct field parameters to a function
I have a Message struct, and a function that creates a new Message and does something with it. 我有一个Message结构,以及一个创建新Message并对其进行处理的函数。
type Message struct {
To string
From string
Body string
}
func Message() {
newMessage := Message{Body: "test"}
// do something with newMessage
}
I'd like to pass the parameters to the struct into the function, kind of like this (obviously not syntactically correct, but you get the gist). 我想将参数传递给struct到函数中,就像这样(显然在语法上不正确,但要领)。
func Message(/*params*/) {
newMessage := Message{/*params*/}
// do something with newMessage
}
The problem is, struct parameters themselves don't have a type, so there's no way to give them directly to a function. 问题是,结构参数本身没有类型,因此无法将它们直接赋予函数。 I could probably give the function a map, and get the parameters out of there, but I want to keep using the message function as simple as possible, avoiding things like this: 我可能可以给函数一个映射,然后从那里获取参数,但是我想继续尽可能简单地使用message函数,避免这样的事情:
Message(Message{/*params*/})
and 和
var params map[string]string
// set parameters
Message(params)
What exactly are you trying to accomplish? 您到底想完成什么? Why don't struct parameters themselves have a type. 为什么结构参数本身不具有类型。 What is wrong with this? 这有什么问题?
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)
}
Output: 输出:
Message: {message to message from message body}
Just pass in a message directly: 只需直接传递一条消息:
func Send(msg Message) {
// do stuff with msg
}
Send(Message{"to","from","body"})
If there are additional properties you need to initialize you can do it like this: 如果还有其他属性需要初始化,可以这样进行:
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",
})
Though it's hard to know the best approach without more information. 尽管没有更多信息,很难知道最好的方法。
I think you want sth like this, but it's not valid style in Golang. 我想您想这样,但是在Golang中这不是有效的样式。
Message(To:'Ray',From:'Jack') 消息(到:“雷”,来自:“杰克”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.