pointer-go

path: courses/go-course/pointer-go.md

- **fileName**: pointer-go
- **Created on**: 2024-09-01 23:09:35

now let's talk about pointer i better way to make the code performance faster and better

username := "yossef"
userPtr := &username // 0x1234213
userPtrValue := *userPtr
// or can decreleade a ptr using var
var ptr *string
ptr = &username

the best use case for pointer in function why let's look at the code to find out:

func main() {
	name := "yossef"
	fmt.Printf("the user one ptr: %p", &name)
	printName(name)	
	return
}

func printName(name string) {
	fmt.Printf("the user two ptr: %p", &name)
	fmt.Printf("the user name is: %s" , name)
}
/*
in the code example there is two variable one in the main and second in local function printName
and we create a 2 variable in the example it's not meaning alot but when you have big project and want to decrease the variable that decraled the better way using a ptr
*/

// using pointer is better
func main() {
	name := "yossef"
	fmt.Printf("the user one ptr: %p", &name)
	printName(&name)	
	return
}

func printName(name *string) {
	fmt.Printf("the user two ptr: %p", name)
	fmt.Printf("the user name is: %s" , *name)
}
/*
now in this example there is a one variable that in the mean function and now we passing the variable ptr to function 
*/
Pointer receiver
type car struct {
	color string
}

func (c *car) setColor(color string) {
	c.color = color
}

func main() {
	c := car{
		color: "white",
	}
	c.setColor("blue")
	fmt.Println(c.color)
	// prints "blue"
}
Non-pointer receiver
type car struct {
	color string
}

func (c car) setColor(color string) {
	c.color = color
}

func main() {
	c := car{
		color: "white",
	}
	c.setColor("blue")
	fmt.Println(c.color)
	// prints "white"
}

continue:modules-go.md
before:map-go.md