Вы находитесь на странице: 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.go
package 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 e"ample.go
The results will e:
100
0
!ou might have e"pected the output to have een 1100 however 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. This
simply means a #copy$ of the val variale is used y the updateValue function.
Lets fi" this so that updateValue will change the val value. In order to do this we need to
pass the val variale y reference. That is, we will pass in the address of the val variale and
then updateValue can 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)
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{(*(.(0 (%1.01 (0*.%1}
fmt.Println("2riginal .tock 3ata:" goog)
}
The results will e:
2riginal .tock 3ata: {(*(.(0 (%1.01 (0*.%1}
'asy enough. (ow, we will modify the contents of the stock struct.
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{(*(.(0 (%1.01 (0*.%1}
fmt.Println("2riginal .tock 3ata:" goog)
modif-.tock(,goog)
fmt.Println("4odi5ed .tock 3ata:" goog)
}
The results will e:
2riginal .tock 3ata: {(*(.(0 (%1.01 (0*.%1}
4odi5ed .tock 3ata: {()*.1 (00.1* (*0.)*}

Вам также может понравиться