variable is a container of value, what type value of you want to assign is data type. golang is static typing that mean you have to ensure what type actually you want to assign to the variable.
Data type Go
There is several data types
- int
- string
- bool
int is data type numeric the value is number without floating point like -90,89,...,0,89,90.
string is data type text the value is text and phrase or word like "Steve", "Hello World", "I love learning golang".
bool is data type logic containt just 2 variant value true
or false
.
Declare variable
There is two way to create variable
package main
import "fmt"
func main() {
var name string
var age int
var graduates bool
name = "Linda"
age = 24
graduates = false
fmt.Printf("%s and i %d years old", name, age)
fmt.Println(graduates)
// OR
name1 := "Linda"
fmt.Println(name1)
}
The first way, declare first variable name
using key var
and following string
as data type so the format is look like.
var variable_name <data_type>
The second one is using :=
to declare variable and assign value, data type will follow the value. From the example we assign "Linda" so variable name1
will have string data type.
Symbol :=
just can be using once, you will get error if you using it at the same variable name. So if you want to change value of name1
just write name = "Linda changed"
package main
import "fmt"
func main() {
name1 := "Linda" // Will set variable name1 as string
fmt.Println(name1)
name1 = "Linda changed"
fmt.Println(name1)
}
Go is static typing, int
value can't assign to variable name1
cause name1
as string
, it will show you compiler error.
package main
import "fmt"
func main() {
name1 := "Linda"
name1 = 1
// Compiler error
fmt.Println(name)
}
All variable that you have declared have to use, if there is a variable that never use, it will get out error compiler
package main
import "fmt"
func main(){
name := "Steve"
age := 17
married := false
fmt.Println(name)
fmt.Println(age)
}
It will show you error because the variable married
never been used. Not only variable the rule is same with package, if you import package for example fmt
, you have use it or you can get error compiler.
Conclusion
We have knew how to create variable and data type so now you can specify what kind of data type you need.
Question:
Why we assign age
as int why not string?
Top comments (0)