4

With the code below how do I add an IP struct to the Server struct's ips array?

import (
    "net"
)

type Server struct {
    id int
    ips []net.IP
}

func main() {
    o := 5
    ip := net.ParseIP("127.0.0.1")
    server := Server{o, ??ip??}
}

Do I even have the ips array correct? Is it better to use a pointer?

1 Answer 1

13

A slice literal looks like []net.IP{ip} (or []net.IP{ip1,ip2,ip3...}. Stylistically, struct initializers with names are preferred, so Server{id: o, ips: []net.IP{ip}} is more standard. The whole code sample with those changes:

package main

import (
    "fmt"
    "net"
)

type Server struct {
    id  int
    ips []net.IP
}

func main() {
    o := 5
    ip := net.ParseIP("127.0.0.1")
    server := Server{id: o, ips: []net.IP{ip}}
    fmt.Println(server)
}

You asked

Do I even have the ips array correct? Is it better to use a pointer?

You don't need to use a pointer to a slice. Slices are little structures that contain a pointer, length, and capacity.

Sign up to request clarification or add additional context in comments.

3 Comments

about the "initializers with names" what do you with anonymous struct in the struct
If you're talking about type embedding, you use the name of the embedded type as the field name in the initializer (e.g., play.golang.org/p/CG1u8AOWOe).
ahhh now i think i understand the table-testing examples in the fmt package. it's like we have to sacrifice the clarity of JSON for having a nice programming language. and that's ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.