简体   繁体   中英

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.

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).

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{/*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.

Message(To:'Ray',From:'Jack')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM