How to add item to array in struct in golang
arrays, go, struct
Solution
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.
Problem
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?