Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add item to array in struct in golang

Tags:

arrays

struct

go

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?

like image 868
Clutch Avatar asked Dec 16 '22 03:12

Clutch


1 Answers

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.

like image 187
twotwotwo Avatar answered Jan 25 '23 22:01

twotwotwo