Need a fresh look because something I do, I get wrong here. I tried to append status to a slice, it wouldn't work
I tried using dereferencing as well
type ServerStatuses []ServerStatus
statuses := new(ServerStatuses)
status := &ServerStatus{
time: time,
available: available,
url: url,
}
statuses = append(statuses, *status)
append
will not work in such case in spite of statuses is a slice.
It's nothing to do with the named type. It's because statuses
is a *ServerStatuses
, which is a pointer to a slice, not a slice. You can only append to slices, not to pointers. Remember that new
returns a pointer to the given type. If you replace new(ServerStatuses)
with ServerStatuses{}
, it works: https://play.golang.org/p/OYdTbLoVifD
In Go, the new
built-in function returns a pointer of specified type. So, new(ServerStatuses)
gives you a pointer of ServerStatuses
, type (*ServerStatuses
).
And also you are using an append statement. But append()
only appends to a slice
. You are trying to append the pointed value of status
var of type SeverStatus
to the var statuses
of type *ServerStatuses
. That's why it's not going as you expect. If we simulate the statement you used against the corresponding types of the var:
statuses = append( statuses, *status )
*ServerStatuses <-- append( *ServerStatuses, ServerStatus )
So, you have to declare statuses
var as a slice
type. For example,
statuses := make(ServerStatuses, 0)
See, an example https://play.golang.org/p/RXETzrxSVqm