Skip to content

Instantly share code, notes, and snippets.

@super1-chen
Created May 15, 2019 15:06
Show Gist options
  • Select an option

  • Save super1-chen/0109f9cfb99a29b70cae858d5fbb2a35 to your computer and use it in GitHub Desktop.

Select an option

Save super1-chen/0109f9cfb99a29b70cae858d5fbb2a35 to your computer and use it in GitHub Desktop.
Snippet from A Tour of Go

Variables

The var statement declares a list of variables; as in function argument lists, the type is last. A var statement can be at package or function level. We see both in this example.

variables.go

package main

import "fmt"

var c, python, java bool

func main() {
	var i int
	fmt.Println(i, c, python, java)
}

Variables with initializers

A var declaration can include initializers, one per variable. If an initializer is present, the type can be omitted; the variable will take the type of the initializer.

variables-with-initializers.go

package main

import "fmt"

var i, j int = 1, 2
var k int

func main() {
	var c, python, java = true, false, "no!"
	fmt.Println(i, j, c, python, java)
	fmt.Println(k)
}

Short variable declarations

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type. Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

shor-variable-declarations.go

package main

import "fmt"

func main() {
	var i, j int = 1, 2
	k := 3
	c, python, java := true, false, "no!"

	fmt.Println(i, j, k, c, python, java)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment