Go Language-Basic ❷

Basic ❷

I'm going to write the understanding of Go from the basics of programming! Go language-Basic ❶ is here

Difference between variable definition and assignment

package main
func main(){
  n := 100
  n := 200
  println(n)
}

//console
:=Error if there is no new variable to the left of

Note the difference between the variable definition ": =" and the assignment "=" Error because variable n is defined twice

Where variables can be used

package main
func main(){
  println(n) //Usage prohibited
  n := 100
  println(n) //Available
}

//console
Error if variable n is not defined

Variables can only be used after they have been defined Error in the console stating "variable n is not defined"

Variables not used

package main
func main(){
  a := 100
  b := 200 //Not in use
  println(a)
}

//console
Error if variable b is not used

Error if there is a variable that is defined but not used Go is designed to generate errors and prevent bugs

Type mismatch

package main
func main(){
  n := 100
  n := "Go" //Not int type
  println(n)
}

//console
string type"Go"Error if cannot be assigned to variable n as int type

You cannot assign a value of a data type that is different from the data type of the variable

Variable arithmetic

package main
func main(){
  n := 100
  println(n + 100)
}

//console
200

Variables can be treated like values

Self-substitution

package main
func main(){
  n := 100
  n = n + 10 //100+Reassign the sum of 10 to the variable n
  println(n)
}

//console
110

Add the number 10 to the value of n, 100, and assign it to n again (self-assignment).

Omission of self-assignment

//prototype//Abbreviated type
n = n + 10       n += 10
n = n - 10       n -= 10
n = n * 10       n *= 10
n = n / 10       n /= 10
n = n % 10       n %= 10
}

"N = n + 10" can be abbreviated as "n + = 10", and this also applies to "-", "*", "/", and "%".

Omission of self-assignment (2)

n = n + 1 → n += 1 → n++
n = n - 1 → n -= 1 → n--
}

The symbol "++" means "add 1 to a variable" On the contrary, "-" means "subtract 1 from the variable".

Can be omitted only when adding or subtracting 1 to the variable

Recommended Posts

Go Language-Basic ❶
Go Language-Basic ❷
Go language-fmt.Scan
Go language-address
Go Language-Functions
Go language-pointer
GO Chokisomemo 1
Go language-iteration
Go language-conditional branching
About Go functions
Go language-standard package
Go class basics
Go language-rand package
About Go Interface
use go module