Builtin func "append" in method for pointer receiver - pointers

Having two types:
type Headers []HeaderItem
type HeaderItem struct { // This one doesn't really matter. Could be any other type
Name string
Value string
}
I would like to add a function with the slice as receiver. How can I do something like this (pseudo-code):
func (h *Headers) AddHeaderItem(item HeaderItem) {
h = &(append( *h, item ))
}
The compiler complains about it, so this doesn't work.
I tried:
func (h Headers) AddHeaderItem(item HeaderItem) {
h = append( h, item )
}
This actually compiles but doesn't do what I want: when later on rangeing over the items, I get an empty result.

Inside the AddHeaderItem() method h is a pointer. You do not want to change the pointer but the pointed value:
func (h *Headers) AddHeaderItem(item HeaderItem) {
*h = append(*h, item)
}
Testing it:
h := Headers{}
fmt.Println(h)
h.AddHeaderItem(HeaderItem{"myname1", "myvalue1"})
fmt.Println(h)
h.AddHeaderItem(HeaderItem{"myname2", "myvalue2"})
fmt.Println(h)
Output:
[]
[{myname1 myvalue1}]
[{myname1 myvalue1} {myname2 myvalue2}]
Try it on the Go Playground.

Don't do this. Don't try too be too clever. Just use a struct with the slice as a member. It adds literally zero overhead, and whoever will have to look at your code later (including you) will be grateful.

Related

Comparing referenced internal struct field to string type in go

Say I have two structs that define a linked list:
....
....
type node struct {
item interface{}
next *node
}
type LinkedList struct {
first *node
N int
}
...
...
and I want to compare the value of the type of the underlying node, say, in a find function where we check if k == node.item such that:
func (l *LinkedList) find (key interface{}) bool {
result := false
if !l.isEmpty() {
for x:= l.first; x != nil; x = x.next {
if x.item == key {
result = true
break
}
}
return result
}
this will not work for the expected find function because the underlying types are different, hence the func will always return false. We can confirm this upon reflecting the type:
fmt.Println(reflect.TypeOf(key), reflect.TypeOf(x.item))
>>> string, *main.node
Tried workarounds?
I've tried asserting the type but alas this does not work and panics
tmp := x.item.(string)
>>>panic: interface conversion: interface {} is *main.node, not string
This case is the same for using fmt.Sprintf(x.item)
I'm a bit stumped as to where to go from here. Is there a way to do this?
Inserting item to linked list
The following snippet should clarify how insertion is handled
func (l *LinkedList) insertFirst(item interface{}) {
var first *node = new(node)
oldfirst := l.first
first.item = item
first.next = oldfirst
l.first = first
l.N++
}
.....
//which gets called somewhere like
var n *node = new(node)
n.item = item
l.insertFirst(n)
.....wait no theres the error!
----------
burak-serdar you are 100% correct that I am inserting the node in the node!
The interface comparison in find() is a valid comparison and it will work if the type of the key and the type of the value stored in the node are the same. However, evidence points to you adding a node in place of a value.

Replace value of interface

I want to replace an interface's value like this:
package main
import "fmt"
type Fooer interface {Foo(string)}
type Foo struct {foo string}
func (f *Foo) Foo(bar string) {f.foo = bar}
var z = &Foo{foo : "new"}
func swap(fooer Fooer) {fooer = z}
func main() {
f := &Foo{foo: "old"}
fmt.Printf("%s (want &{old})\n", f)
swap(f)
fmt.Printf("%s (want &{new})", f)
}
But i get:
&{old}
&{old}
I tried around with various calls (fooer *= z, *fooer = *z, ..) but I cant seem to get it right.
You can try this example at play.golang: http://play.golang.org/p/EZEh3X8yHC
Okay, I think it works like this:
func swap(fooer Fooer) {
foo, _ := fooer.(*Foo)
*foo = *z
}
Like most things in Go, interfaces are simply values. Assigning a new value within a function isn't going to change the value copied into the function arguments.
Because you want to replace the interface value, you need a pointer to the value just like you would any other. It's a very rare case where you could use a pointer to an interface: http://play.golang.org/p/EZEh3X8yHC
func swap(fooer *Fooer) {
z := Fooer(&Foo{foo: "new"})
*fooer = z
}
func main() {
var f Fooer = &Foo{foo: "old"}
fmt.Printf("%s (want &{old})\n", f)
swap(&f)
fmt.Printf("%s (want &{new})", f)
}
But, since a pointer to an interface is almost always a mistake (you can see we have to be very explicit to make this work), you should really have a good reason for implementing something this way, and document it well.
What you most likely want is to extract the pointer from the interface, and assign a new value in there (which is what you added to end of your question). This is a much better construct, but the type must match, so the interface isn't needed.

Pointer problems

TL;DR Somehow, I am appending a pointer to a list instead of the object within a for loop of objects so at the end the entire slice is composed of the same object multiple times. I just don't know how to fix that.
The Long Way
I am still having a super hard time trying to figure out pointers in go. I posted a question yesterday and got some help but now I am stuck on a slightly different issue in the same piece of code.
I am working with gocql and cqlr go packages to try and bit a small object mapper for my Cassandra queries. Essentially the problem I am having is I am appending what appears to be a pointer to an object, not a new instance of the obj to the array. How do I fix that? I have tried adding & and * in front of value but that doesn't seem to work. How do I fix these? The bind function needs an & according to their docs.
Code
type Query struct {
query string
values interface{}
attempts int
maxAttempts int
structType reflect.Type
}
func (query Query) RetryingQuery() (results []interface{}) {
var q *gocql.Query
if query.values != nil {
q = c.Session.Query(query.query, query.values)
} else {
q = c.Session.Query(query.query)
}
bindQuery := cqlr.BindQuery(q)
value := reflect.New(query.structType).Interface()
for bindQuery.Scan(value) {
fmt.Println(value)
results = append(results, value)
}
return
}
The docs ask for var value type then in bind you would pass &value. I quoted the docs below.
var t Tweet
var s []Tweet
for b.Scan(&t) {
// Application specific code goes here
append(s, t)
}
The issue is I cannot directly go var value query.structType to define its type then pass the reference of that to bindQuery.Scan().
What is printed
&{result1 x86_64 24 3.2.0-74-generic Linux}
&{result2 x86_64 24 3.19.0-25-generic Linux}
&{result3 x86_64 4 3.13.0-48-generic Linux}
&{result4 x86_64 2 3.13.0-62-generic Linux}
&{result5 x86_64 4 3.13.0-48-generic Linux}
What is in the slice
Spoiler, it is result5 repeated over and over. I understand that I am just appending the pointer to same object to the list and that every loop iteration the object is changed and that changes all the results in the slice to that new object. I just don't know how to fix it.
[{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"},{"hostname":"result5","machine":"x86_64","num_cpus":4,"release":"3.13.0-48-generic","sysname":"Linux"}]
Well I can at least tell you what you're doing. bindQuery takes a pointer. It changes the value stored at the address.
What you're essentially doing is this:
package main
import "fmt"
func main() {
var q int
myInts := make([]*int, 0, 5)
for i := 0; i < 5; i++ {
q = i
fmt.Printf("%d ", q)
myInts = append(myInts, &q)
}
fmt.Printf("\n")
for _, value := range myInts {
fmt.Printf("%d ", *value)
}
fmt.Printf("\n")
fmt.Println(myInts)
}
Which, as you can probably guess, gives you this:
0 1 2 3 4
4 4 4 4 4
[0x104382e0 0x104382e0 0x104382e0 0x104382e0 0x104382e0]
Things get a little more confusing with reflect. You can get your type as an interface, but that is it (unless you want to play with unsafe). An interface, in simple terms, contains a pointer to the original type underneath (and some other stuff). So in your function you are passing a pointer (and some other stuff). Then you're appending the pointer. It might be nice just to get concrete and type switch your interface. I assume you know what types it could be. In which case you'd have to have something along these lines:
package main
import (
"fmt"
"reflect"
)
type foo struct {
fooval string
}
type bar struct {
barval string
}
func main() {
f1 := foo{"hi"}
f2 := &foo{"hi"}
b1 := bar{"bye"}
b2 := &bar{"bye"}
doSomething(f1)
doSomething(f2)
doSomething(b1)
doSomething(b2)
}
func doSomething(i interface{}) {
n := reflect.TypeOf(i)
// get a new one
newn := reflect.New(n).Interface()
// find out what we got and handle each case
switch t := newn.(type) {
case **foo:
*t = &foo{"hi!"}
fmt.Printf("It was a **foo, here is the address %p and here is the value %v\n", *t, **t)
case **bar:
*t = &bar{"bye :("}
fmt.Printf("It was a **bar, here is the address %p and here is the value %v\n", *t, **t)
case *foo:
t = &foo{"hey!"}
fmt.Printf("It was a *foo, here is the address %p and here is the value %v\n", t, *t)
case *bar:
t = &bar{"ahh!"}
fmt.Printf("It was a *bar, here is the address %p and here is the value %v\n", t, *t)
default:
panic("AHHHH")
}
}
You could also just keep calling value = reflect.New(query.structType).Interface() inside of the loop which will give you new interfaces every time. Reassigning value after every append. Last time through the loop would make one extra though..

Difference between &Struct{} vs Struct{}

Is there a reason why I should create a struct using &StructName{} instead of Struct{}? I see many examples using the former syntax, even in the Effective Go Page but I really can not understand why.
Additional Notes:
I'm not sure whether I explained my problem well with these two approaches so let me refine my question.
I know that by using the & I will recieve a pointer instead of a value however I would like to know why would I use the &StructName{} instead of the StructName{}. For example, is there any benefits of using:
func NewJob(command string, logger *log.Logger) *Job {
return &Job{command, logger}
}
instead of:
func NewJob(command string, logger *log.Logger) Job {
return Job{command, logger}
}
Well, they will have different behavior. Essentially if you want to modify state using a method on a struct, then you will need a pointer, otherwise a value will be fine. Maybe an example will be better:
package main
import "fmt"
type test_struct struct {
Message string
}
func (t test_struct)Say (){
fmt.Println(t.Message)
}
func (t test_struct)Update(m string){
t.Message = m;
}
func (t * test_struct) SayP(){
fmt.Println(t.Message)
}
func (t* test_struct) UpdateP(m string) {
t.Message = m;
}
func main(){
ts := test_struct{}
ts.Message = "test";
ts.Say()
ts.Update("test2")
ts.Say() // will still output test
tsp := &test_struct{}
tsp.Message = "test"
tsp.SayP();
tsp.UpdateP("test2")
tsp.SayP() // will output test2
}
And you can run it here go playground
Assuming you know the general difference between a pointer and a value:
The first way allocates a struct and assigns a pointer to that allocated struct to the variable p1.
p1 := &StructName{}
The second way allocates a struct and assigns a value (the struct itself) to the variable s.
Then a pointer to that struct may be assigned to another variable (p2 in the following example).
s := StructName{}
p2 := &s

Go: edit in place of map values

I wrote a simple program using the Go Playground at golang.org.
The output is obviously:
second test
first test
Is there a way to edit the map value in place? I know I can't take the andress of a.Things[key]. So, is setting a.Things[key] = firstTest the only way to do it? Maybe with a function ChangeThing(key string, value string)?
You could do it by making the values of your map pointers to another struct.
http://play.golang.org/p/UouwDGuVpi
package main
import "fmt"
type A struct {
Things map[string]*str
}
type str struct {
s string
}
func (a A) ThingWithKey(key string) *str {
return a.Things[key]
}
func main() {
variable := A{}
variable.Things = make(map[string]*str)
variable.Things["first"] = &str{s:"first test"}
firstTest := variable.ThingWithKey("first")
firstTest.s = "second test"
fmt.Println(firstTest.s)
fmt.Println(variable.ThingWithKey("first").s)
}
You can use a pointer as the map value http://play.golang.org/p/BCsmhevGMX

Resources