Golang - Pointers
Transcript of Golang - Pointers
-
8/10/2019 Golang - Pointers
1/3
Im assuming you already have Go up and running, if not make sure to do that first.
Lets start with a very simple application that simply takes a value and runs a calculation on it.
Create a new file and call it: example.gopackage main
import "fmt"
func updateValue(val int) {
val = val + 100
}
func main() {
val := 1000
updateValue(val)
fmt.Println("val:" val)
}
If you run this code like so:
! go run eample.go
The results will e:
100
0
!ou might have e"pected the output to have een1100however you need to keep in mind
that y default when you pass an argument to a function in Go it will e copied y value. Thissimply means a #copy$ of thevalvariale is used y the updateValuefunction.
Lets fi" this so that updateValuewill change thevalvalue. In order to do this we need to
pass thevalvariale y reference. That is, we will pass in the address of thevalvariale and
then updateValuecan change that value.
package main
import "fmt"
func updateValue(#omeVal $int #omeVal% $&oat') {
$#omeVal = $#omeVal + 100
$#omeVal% = $#omeVal% + 1.*
}func main() {
val := 1000
val% := ne(&oat')
updateValue(,val val%)
fmt.Println("val:" val)
http://www.giantflyingsaucer.com/blog/?p=4649http://www.giantflyingsaucer.com/blog/?p=4649 -
8/10/2019 Golang - Pointers
2/3
fmt.Println("val%:" $val%)
}
The results will e:
val: 1100
val%: 1.*Lets kick this up a it and add in a struct. %e will create a struct to hold a stocks high, low
and closing market price.
&ere is the code:
package main
import "fmt"
t-pe tock #truct {
/ig/ &oat'
lo &oat' clo#e &oat'
}
func main() {
goog := tock{*. %1.01 *.%}
fmt.Println("2riginal tock 3ata:" goog)
}
The results will e:
2riginal tock 3ata: {*. %1.01 *.%}
'asy enough. (ow, we will modify the contents of thestockstruct.package main
import "fmt"
t-pe tock #truct {
/ig/ &oat'
lo &oat'
clo#e &oat'
}
func modif-tock(#tock $tock) {
#tock./ig/ = *.10
#tock.lo = 00.1*
#tock.clo#e = *0.*
}
func main() {
goog := tock{*. %1.01 *.%}
fmt.Println("2riginal tock 3ata:" goog)
http://tour.golang.org/#25http://tour.golang.org/#25 -
8/10/2019 Golang - Pointers
3/3
modif-tock(,goog)
fmt.Println("4odi5ed tock 3ata:" goog)
}
The results will e:
2riginal tock 3ata: {*. %1.01 *.%}
4odi5ed tock 3ata: {*.1 00.1* *0.*}