[Go]Change value to a struct in an array

You cannot change the value of a struct directly to an array, you will need to dereference the pointer and change the value.

There are two methods one is to reference the object’s index and change the struct value the other is to pass in the memory address of the current object index and use the pointer to change the value.

package main

import "fmt"

type device struct {
	hostname string
	ip       string
}

func main() {
	var devices []device
	devices = append(devices,
		device{hostname: "linux", ip: "192.168.1.100"},
		device{hostname: "cisco_r1", ip: "192.168.1.254"},
		device{hostname: "cisco_sw1", ip: "192.168.1.200"},
		device{hostname: "new_router", ip: ""},)

	for i, v := range devices {
		if v.ip == "" {
			// devices[i].ip = "192.168.1.222"
			ptr := &devices[i]
			ptr.ip = "192.168.1.222"
		}
	}
	fmt.Println(devices)
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s