Back to archive
|6 min read

Go Basics: Variables, Types, and Signatures Explained

A comprehensive overview of Go's foundational syntax, covering packages, variable declarations, function signatures, and the core principles of its static type system.

Variable_DeclarationStatic_TypingType_InferenceGolangBackend/GoSyntax/Basics

1.1#

Concept Formatted printing#

Fomarted printing Formatted printing in Go is the same as(identical to) in C. It retains standard verbs such as %d and %f. Additionally, Go introduced %g, which functions similarly to %f but automatically trims trailing zeros.

Vocabulary List#

这里format和print都是动词,需要将其转化为名词短语,英语里只有the same as
retain:保留
introduced/adds:引入/补充
which functions is similar to %f
remove/elimate:消除,但在处理字符串或者数字末尾多余部分时,程序员大多使用trim
末尾的零:在计算机中式专有名词:tralling zeros
be exported:被导出,等同于public
Parentheses:()圆括号       Brackets:[]方括号      Curly braces{}:花括号

Concept Control Access#

Control Access: GO elimates the access control keywords such as public and private,instead,access control is directly tied to the capitalization of the first letter.

package main
import (
	"fmt"
	"math"
)
func main(){
fmt.Println(math.pi)
}

print:./prog.go:9:19: undefined: math.pi (but have pi)

for printing: Go is very smart. It knows you meant to use Pi

package main
import (
	"fmt"
	"math"
)
func main(){
fmt.Println(math.Pi)
}

print:3.141592653589793

Vocabulary List#

elimate:消除,淘汰
Access Control:专有名词,访问控制(控制权限)
Visibility:可见性
tie to:与....绑定
Capitalization:大写
Case:Uppercase大写,Lowercase:小写
letter:26个英文字母的统称
Capital letter:大写字母

Concept Functions#

take arguments or parameters: A function can take zero or more arguments or parameters,and their type comes after the parameter name. Argument vs Parameters: A parameter acts as a placeholder, while an argument is the actual value passed in.

package main

import "fmt"

func add(x int,y int)int{
return x+y
}
func main(){
	fmt.Println(add(42,13))
}
print: 55

When two or more consecutive named function parameters share a type ,you can omite the type from all but the last

x int,y int
==
x,y int

Multiple results: A function can return Mutiple results,In the function signature, the return types must be wrapped in a pair of parentheses following the parameter list. the "swap" of Go: Go support tuple assignment, which allows you to swap two variables in a single line, No temporary variable is needed.

a, b = b, a

":=" Short Variable Declaration: This operator is equivalent to combining declaration and initialzation into one step. The := operator is only available inside functions. At the package level(outside),every statement must begin with a keyword such as var or func (Outside a function, Keywords are)

package main

import "fmt"

func swap(x, y string)(string, string){
	return y,x
}
func main(){
	a, b :=swap("hello", "world")
	fmt.Println(a, b)
}
print: world hello

named return values: In Go,we can assign names to a function'sreturnvalues. These names can be used as variables within the function naked return: In go, a naked return returns the named return values. This is typically used in short function to keep them concise. Package Level and Function level Var: Package level: var c, python, java bool var variable_name type these variables are accessible throughout the entire package. feature: can declare multiple variables in one line Function level: var c, python, java bool var variable_name type these variables are accessible throughout the entire package. "zero phomane": Go automatically assigns a default value(zero,default) to variables that are not explicity initialized. Numeric types(int,float):0 Boolean type:false String type:""

package main

import "fmt"

func split(sum int)(x,y int){
	x= sum*4/9
	y=sum-x
	return
}
func main(){
	fmt.Println(split(17))
}
print: 7 10
print all named variables in this function

Variable 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. Variable declarations be "factored" into blocks:

	var ToBe bool = false
	var Maxint uint64 = 1<<64-1
	var Z complex128 = cmpl.Sqrt
var (
	 ToBe bool = false
	 Maxint uint64 = 1<<64-1
	 Z complex128 = cmpl.Sqrt
)
The code snippets above are equivalent.

Wide on System: The intuint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. Type Conversions: Unlike in C, in Go assignment between items of different type requires an explicit conversion.

	var f float64 = math.Sqrt(float64(x*x + y*y))
	//the math.Sqrt function requires a float64,so we use float64() to convert the in result.

Different of float32 and float64

feature float32 float64
Memory 32 bits/4bytes 64 bits/8bytes
Precision ~7decimal digits ~15decimal digits
Go Default must be explicitly declared default for float literals
Best For Low memory、3D Graphics、Sensors General Purpose、Math、Finance
Type inference:
Go infers a variable's type based on the precision of the numeric constant.

Constants: Constants are declared like variables,but with the const keyword Constants can be character, string, boolean, or numeric values. Constants cannot be declared using the := syntax.

const World = "世界"
const Pi = 3.14
const Truth = true

Numeric Constants: Go constants are untyped and high-precision. They act as the type required by their context.

Vocabulary List#

signature:函数签名(指函数的定义格式)
equivalent to:等同于
declaration:声明
initialization:初始化
tuple assignment:元组赋值
wrap:包裹
naked return:裸返回
mandatory:强制性的,必须遵守的规则
available:可用的
explicit:明确的,直白的
implicit:隐式的
numeric:数字的,它强调”属于数字这一类别“,numeric types:是一个全家桶概念,他统称了所有用来表示数字的数据类型
either...or:要么....要么....