Using pointer member in struct

Hi,
I have seen that some people use pointer type member to struct and would like to know what is the advantages in this over normal one. (They have used this in lib. which will send the data to other micro-services in xml format)

type Employee struct{

Name *string
DepName  *string

}

I don’t know why somebody is doing this in your specific case. But the difference should be obvious:

package main

import "fmt"

type Foo struct {
	a *string
	b string
}

func (foo Foo) String() string {
	return fmt.Sprintf("Foo(a=%s, b=%s)", *foo.a, foo.b)
}

func main() {
	a := "a-orig"
	b := "b-orig"

	// Creat two instances.
	foo := Foo{a: &a, b: b}
	fmt.Println(foo)

	bar := Foo{a: &a, b: b}
	fmt.Println(bar)

	// Now we change `a` and `b`.
	a = "a-changed"
	b = "b-changed"

	// But only the change to `a` has effect in the structs.
	fmt.Println(foo)
	fmt.Println(bar)
}

Output:

Foo(a=a-orig, b=b-orig)
Foo(a=a-orig, b=b-orig)
Foo(a=a-changed, b=b-orig)
Foo(a=a-changed, b=b-orig)

see https://play.golang.org/p/ZL-4nBksGN1

I suspect the API distinguishes between a nil string and an empty string. Perhaps a nil string is omitted from the XML where an empty string is an empty attribute (e.g. <Employee Name=""/> vs. <Employee />)

2 Likes

Yes .this is the reason…if nil then xml marsgal not taking value

Thank you

Thank you. Real reason behind that might be xml Marshall dont consider if the value is nil.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.