Modifying Variable Values
We've learned how to declare a variable. Now, let's understand how to modify the value of a variable.
Take a look at the following program, which prints the value of myVariable using the Println function:
index.go
1234567package main import "fmt" func main() { var myVariable = 7 fmt.Println(myVariable) // Using the name of the variable ('myVariable') we can access and show it's value }
We can use the following syntax for assigning a different value to the variable:
index.go
1myVariable = 9
Notice that this time, we omit the var keyword because we are not declaring a new variable. Now, let's add this line to the program:
index.go
123456789package main import "fmt" func main() { var myVariable = 7 fmt.Println(myVariable) // Outputs 7 myVariable = 9 fmt.Println(myVariable) // Outputs 9 }
In the code above, we employed the var keyword to declare a variable. Alternatively, we can use the := operator for variable declaration. In such a case, the code will appear as follows:
index.go
123456789package main import "fmt" func main() { myVariable := 7 fmt.Println(myVariable) // Outputs 7 myVariable = 9 fmt.Println(myVariable) // Outputs 9 }
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain the difference between using `var` and `:=` for variable declaration?
What happens if I try to assign a value to a variable that hasn't been declared yet?
Can you show an example of modifying a variable's value in a complete program?
Awesome!
Completion rate improved to 1.96
Modifying Variable Values
Swipe to show menu
We've learned how to declare a variable. Now, let's understand how to modify the value of a variable.
Take a look at the following program, which prints the value of myVariable using the Println function:
index.go
1234567package main import "fmt" func main() { var myVariable = 7 fmt.Println(myVariable) // Using the name of the variable ('myVariable') we can access and show it's value }
We can use the following syntax for assigning a different value to the variable:
index.go
1myVariable = 9
Notice that this time, we omit the var keyword because we are not declaring a new variable. Now, let's add this line to the program:
index.go
123456789package main import "fmt" func main() { var myVariable = 7 fmt.Println(myVariable) // Outputs 7 myVariable = 9 fmt.Println(myVariable) // Outputs 9 }
In the code above, we employed the var keyword to declare a variable. Alternatively, we can use the := operator for variable declaration. In such a case, the code will appear as follows:
index.go
123456789package main import "fmt" func main() { myVariable := 7 fmt.Println(myVariable) // Outputs 7 myVariable = 9 fmt.Println(myVariable) // Outputs 9 }
Thanks for your feedback!