Friday, October 4, 2024
HomeGolangPointers are nonetheless a thriller to me

Pointers are nonetheless a thriller to me


@hollowaykeanho Thanks for the detailed clarification, issues begin to be clearer :slight_smile:

Simply to ensure I absolutely perceive your first case

  1. get/set a set of information saved in a selected reminiscence fairly than copy-pasting everywhere in the locations (e.g. operate taking non-pointer sort are normally copied as duplicate and never instantly modifying the unique one).

Does this imply that if I do that:

func Calculate(i, j int) (int, int) {
	fmt.Println(i) // learn i, duplicate?
	i = 21         // set new worth i, into its duplicate?
	fmt.Println(i) // see the brand new worth of i, from its duplicate?

	j = j / 37     // divide j
	fmt.Println(j) // see the brand new worth of j

	return i, j //these are the duplicates proper? they may get dealt with by the GC?
}

func predominant() {
	i := 42
	j := 2701
	i, j = Calculate(i, j)

	fmt.Printf("After caculate i is: %vn", i) // you will not get 42
	fmt.Printf("After caculate j is: %vn", j) // you will not get 2701
}

i and j are duplicated when used inside Calculate? Which means that
i = 21 and j = j / 37 are literally allocating new addresses into the reminiscence, fairly than modifying the already allotted ones instantly?

If that’s the case, what would occur if the Calculate operate is as observe:

func Calculate(i, j int) (int, int) {
	m := i / 2        
	n := j / 37

	return m, n
}

m and n are for certain allotted. What about i and j, do they get duplicated right here?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments