Variable on Golang
M Fariz Wisnu prananda
Posted on October 30, 2021
so now i will tell about variable in golang.
in golang, when the variable declaration must be followed by its data type. this concept is manifest typing . an example like this
package main
import "fmt"
func main(){
var firstName string = "Sakura "
var lastName string
lastName = "endo"
fmt.Printf("halo %s %s!\n", firstName, lastName)
}
the result is
like the code above, I write down the variable followed by the name and data type
How to declare variable using var
conditions in variable declaration with var like this
- Declaration without value
var <name-variable> <type-data>
2.Declaration with value
var <name-variable> <type-data> = <value>
Example
var Name string
var Hobby string = "Football"
What is the use of "fmt.Printf()" ?
the function is the same as Println, but the output is defined at the beginning, in the "hello %s %s!\n" section, %s will be replaced with a string where the string is filled with the value of the 2nd to 3rd parameter and so onof the parameter.
fmt.Printf("Hi %s %s", firstname,lastname)
fmt.Printf("Hi "+ firstname + lastname + "!")
in addition to using "%s" to connect between strings, you can also use "+" .this is called string concatenation
Multi-variable declaration
This way, we can declare multiple variables with just 1 line.
Example:
var firts,second,third string
firsts,second, third = "1","2","3"
easy and very simple,could be more concise this way
var firts,second,third string = "1","2","3"
or
firts,second,third := "1","2","3"
End
Thanks for reading, don't forget to like and share and that's how to declare variable in golang!.
Golang is so much fun
Posted on October 30, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.