DEV Community

Cover image for Variable on Golang
M Fariz Wisnu prananda
M Fariz Wisnu prananda

Posted on • Updated on

Variable on Golang

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)
}
Enter fullscreen mode Exit fullscreen mode

the result is

result

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

  1. Declaration without value
var <name-variable> <type-data>
Enter fullscreen mode Exit fullscreen mode

2.Declaration with value

var <name-variable> <type-data> = <value>
Enter fullscreen mode Exit fullscreen mode

Example

var Name string
var Hobby string = "Football"
Enter fullscreen mode Exit fullscreen mode

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 + "!")
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

easy and very simple,could be more concise this way

var firts,second,third string = "1","2","3"
Enter fullscreen mode Exit fullscreen mode

or

firts,second,third := "1","2","3"
Enter fullscreen mode Exit fullscreen mode

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

Top comments (3)

Collapse
 
tingwei628 profile image
Tingwei

typo "Variabel"

Collapse
 
xvbnm48 profile image
M Fariz Wisnu prananda

thanks for feedback!

Collapse
 
xvbnm48 profile image
M Fariz Wisnu prananda

sorry for my english, thanks for feedback!