本文记录通过 YouTube-Learn Go Programming - Golang Tutorial for Beginners 学习 Golnag 基础知识的一些笔记。
[Learn Go Programming - Golang Tutorial for Beginners](Learn Go Programming - Golang Tutorial for Beginners - YouTube)
Learn Go Programming - Golang Tutorial for Beginners
Go (Golang)
- Strong and statically typed
- Excellent community
- Key features
- Simplicity
- Fast compile times
- Garbage collected
- Built-in concurrency
- Compile to standalone binaries
Go 'Hello,World!'
package main
import(
"fmt"
)
func main(){
fmt.Println("Hello,World!")
}
Setting Up a Development Environment
Ensure Path under System Variables has the “C:\Go\bin” variable in it.
Environment Variables:"GOPATH"
Test and ensure
go get github.com/golang/example/hello
VARIABLES
AGENDA
- Variable declaration
- Redeclaration and shadowing 重新声明和阴影
- Visibility
- Naming conventions 命名约定
- Type conversions 类型转换
3 ways to declare variables
var i int
i = 42
var j int = 27
k := 99
fmt.Println(i)
fmt.Printf()
var j int = 27
fmt.Printf("%v , %T",j,j)
// OUT PUT:
// 27 int
package var block
var i int = 42
var actorName string = "Elisabeth Sladen"
var companion string = "Sarah Jane Smith"
var doctorNumber int = 3
var season int = 11
// ==>>
var (
i int = 42
actorName string = "Elisabeth Sladen"
companion string = "Sarah Jane Smith"
doctorNumber int = 3
season int = 11
)
variable Shadowing
package main
import "fmt"
var i int = 42
func main() {
var i int
i = 42 // Shadowing
fmt.Printf("%v , %T",i,i)
}
Visibility
var i int = 42 // package
var I int = 99 // gobal
func main() {
var i int
i = 42
fmt.Printf("%v , %T",i,i)
}
Naming conventions
- Variable length is related to life cycle
- Camel-Case(lower camel case)
Type conversions
var i int = 42
fmt.Printf("%v,%T\n",i,i)
var j string
j = string(i)
fmt.Printf("%v,%T",j,j)
// OUT PUT
// 42,int
// *,string
// # 42 for Unicode
The right way:
(use "ctrconv" package)
package main
import (
"fmt"
"strconv"
)
func main() {
var i int = 42
fmt.Printf("%v,%T\n",i,i)
var j string
j = strconv.Itoa(i)
fmt.Printf("%v,%T",j,j)
}
SUMMARY
-
Variable declaration
- var foo int
- var foo int = 42
- foo := 42
-
Can't redeclare variables, but can shadow them
-
All variables must be used
-
Visibility
- lower case first letter for package scope
- upper case first letter to export
- no private scope
-
Naming conventions
- Pascal or camelCase
- Capitalize acronyms (HTTP,URL)
- As short reasonable
- longer names for longer lives
- Pascal or camelCase
-
Type conversions
- destinationType(variable)
- use strconv package for string
PRIMITIVES
AGENDA
- Boolean type
- Numberic type
- Integers
- Floating point
- Complex numbers
- Text types
Boolean type
var n bool = true
fmt.Printf("%v,%T",n,n)
n := 1==1
m := 1==2
fmt.Printf("%v,%T\n",n,n)
fmt.Printf("%v,%T\n",m,m)
// OUT PUT
// true bool
// false bool
var n bool
fmt.Printf("%v,%T",n,n)
// OUT PUT
// false bool
// # The default value is 0, which means false
Numberic type
basic int:
uint
type conversions:
var a int = 10
var b int8 = 3
fmt.Printf(a+int(b)) // must conversions
Arithmetic operation
Logic operation
a := 10 // 1010
b := 3 // 0011
fmt.Println(a & b) // 0010
fmt.Println(a | b) // 1011
fmt.Println(a ^ b) // 1001
fmt.Println(a &^ b) // 0100
Shift operation
a := 8 // 1000
fmt.Println(a << 3) // 0100 0000B 64D 2^3 * 2^3 = 2^6
fmt.Println(a >> 3) // 0001B 1D 2^3 / 2^3 = 2^0
float
n := 3.14
n = 13.7e72
n = 2.1E14
fmt.Printf("%v,%T",n,n)
Text Type
n := "this is a string"
fmt.Printf("%v,%T",n,n)
You can treat string as an array
n := "this is a string"
fmt.Printf("%v,%T",string(n[2]),n[2])
// OUT POUT
105,uint8
[]byte(string)
Put each character in the string into a byte array
n := "this is a string"
b := []byte(n)
fmt.Printf("%v,%T\n",b,b)
// OUT PUT
[116 104 105 115 32 105 115 32 97 32 115 116 114 105 110 103],[]uint8
Declaration rune(字符)
r := 'a'
fmt.Printf("%v,%T",r,r)
var r rune = 'a'
fmt.Printf("%v,%T",r,r)
SUMMARY
-
Boolean type
- Value are true of false
- Not an alias for other types (e.g. int)
- Zero value is false
-
Numeric types
- Integers
- Signed integers
- int type has verying size, but min 32 bits
- 8 bit(int8) through 64 bit (int64)
- Unsigned integers
- 8 bit (byte and uint8) through 32 bit(uint32)
- Arthmetic operations
- Addition, subreaction, multiplication, dicision, remainder
- Bitwise operations (Logic operations)
- And, or, xor, and not
- Zero value is 0
- Can't mix types in same family ! (uint16 + uint 32 = error)
- Floating point numbers
- Follow IEEE-754 standard
- Zero value is 0
- 32 and 64 bit versions
- Literal styles
- Decimal (3.14)
- Exponential(13e18 or 2E10)
- mixed(13.7e12)
- Arithmetic operations
- Addition, subtraction, multiplication, division
- Complex numbers
- Zero value is (0+0i)
- 64 ad 128 bit versions
- Built-in functions
- complex - make complex numbers from two floats
- real - get real part as float
- imag - get imaginary part as float
-
Text types
- Strings
- UTF-8
- Immutable
- Can be concatenated with plus(+) operator
- Can be converted to []byte
- Rune
- UTF-32
- Alias for int32
- Special methods normally required to process
- e.g.strings.Reader#ReadRune
- Strings
CONSTANTS
AGENDA
- Naming convention
- Typed constants
- Untyped constants
- Enumerated constants
- Rnumerated constants
Naming convention
小驼峰
const myConst int = 99
// myConst = 33 error: cannot assign to myConst
fmt.Printf("%v,%T",myConst,myConst)
const a int = 14
const b string = "foo"
const c float32 = 3.14
const d bool = true
fmt.Printf("%v,%T\n",a,a)
fmt.Printf("%v,%T\n",b,b)
fmt.Printf("%v,%T\n",c,c)
fmt.Printf("%v,%T\n",d,d)
// OUT PUT
14,int
foo,string
3.14,float32
true,bool
shadowing
const a int = 99
func main() {
const a int = 14
fmt.Printf("%v,%T",a,a)
}
// OUT PUT
14,int
The compiler automatically infers the type:
const a = 422
var b int16 = 25
fmt.Printf("%v,%T\n",a+b,a+b)
Enumerated constants
const (
a = iota
b // == b = iota
c // == c ==iota)
const (
a2 = iota
)
func main() {
fmt.Printf("%v,%T\n",a,a)
fmt.Printf("%v,%T\n",b,b)
fmt.Printf("%v,%T\n",c,c)
fmt.Printf("%v,%T\n",a2,a2)
}
// OUT PUT
0,int
1,int
2,int
0,int
const (
catSpecialist = iota // 0
dogSpecialist // 1
snakeSpecialist // 2
)
func main() {
var specialistType int = catSpecialist // specialistType default 0 , the catSpecialist 0 , so true
fmt.Printf("%v,%T",specialistType == catSpecialist)
}
若不需要 iota 的 0 可以使用 _
来初始化
const (
_ = iota // 0
catSpecialist // 1
dogSpecialist // 2
snakeSpecialist // 3
)
func main() {
var specialistType int // specialistType default 0 , the catSpecialist 1 , so true
fmt.Printf("%v,%T",specialistType == catSpecialist)
}
Example of shift operation(MB,GB...)
const (
_ = iota // ignore first value by assigning to blank identifier
KB = 1 << (10 * iota)
MB
GB TB PB EB ZB YB)
func main() {
fileSize := 4000000000.
fmt.Printf("%.2fGB",fileSize/GB)
}
// OUT PUT
// 3.75 GB
角色验证
const (
isAdmin = 1 << iota
isHeadquarters
canSeeFinancials
canSeeAfrica
canSeeAsia
canSeeEurope
canSeeNorthAmerica
canSeeSouthAmerica)
func main() {
var roles byte = isAdmin | canSeeFinancials | canSeeEurope
fmt.Printf("%b\n",roles)
fmt.Printf("Is Admin? %v \n",isAdmin & roles == isAdmin)
fmt.Printf("Is HQ? %v \n",isHeadquarters & roles == isHeadquarters)
}
SUMMARY
- Immutable, but can be shadowed
- Replaced by the compiler at compile time
- Value must be calculable at compile time
- Named like variable
- PascalCase for exported constants
- camelCase for internal constants
- Typed constants work like immutable variables
- Can interoperate only with same type
- Untyped constants work like literals
- Can interoperate with similar types
- Enumerated constants
- Special symbol iota allows related constants to be created easily
- Iota starts ao 0 in each const block and increments by one
- Watch out of constant values that match zero values for variables
- Enumerated expressions
- Operaiongs that can be determined at compile time are allowed
- Arithmetic
- Bitwise operations
- Bitshifting
- Operaiongs that can be determined at compile time are allowed
ARRAYs AND SLICES
AGRNDA
-
Arrays
- Creation
- Built-in functions
- Working with arrays
-
Slices
- Creation
- Built-in functions
- Working with slices
ARRAYS
package main
import "fmt"
func main() {
// Don't use array
grade1 := 97
grade2 := 85
grade3 := 93
fmt.Printf("Grades: %v, %v, %v \n",grade1,grade2,grade3)
// use array
grades := [3]int{97,83,34}
fmt.Printf("Grades: %v \n",grades)
ignoreSizeGrades := [...]int{123,1123,123}
fmt.Printf("ignore_size_grades: %v \n", ignoreSizeGrades)
var students [3]string
fmt.Printf("Students: %v \n",students)
students[0] = "Lisa"
students[1] = "Skyzc"
students[2] = "Arnold"
fmt.Printf("Students: %v \n",students)
fmt.Printf("Student #0: %v \n",students[0])
fmt.Printf("Student #1: %v \n",students[1])
fmt.Printf("Student #2: %v \n",students[2])
// len()
fmt.Printf("Number of Students: %v\n",len(students))
// Two-dimensional array
var identityMatrix [3][3]int =[3][3]int {[3]int{1,0,0},[3]int{0,1,0},[3]int{0,0,1}}
fmt.Println(identityMatrix)
var identityMatrixNew [3][3]int
identityMatrixNew[0] = [3]int{1,0,0}
identityMatrixNew[1] = [3]int{0,1,0}
identityMatrixNew[2] = [3]int{0,0,1}
fmt.Println(identityMatrixNew)
// defence other programming language
a := [...]int{1,2,3}
b := a // 相当于复制了一个数组的值,开辟了新的空间
// b := &a // b 指向 a 的地址,没有新空间产生
b[1] = 5
fmt.Println(a)
fmt.Println(b)
fmt.Println(a)
// 数组编译时,必须是固定的大小,所以引出了切片 (slices)
}
SLICES
[]int
a := []int{1,2,3} // [] 中不加 ... 就是声明一个切片
b := a
b[1] =5
fmt.Println(a)
fmt.Println(b)
fmt.Printf("Length: %v\n", len(a))
fmt.Printf("Capacity: %v\n", cap(a))
a[start:end]
a := []int{1,2,3,4,5,6,7,8,9,10}
b := a[:] // slice of all elements
c := a[3:] // slice from 4th element to end
d := a[:6] // slice first 6 elements
e := a[3:6] // slice the 4th,5th and 6th elements
a[5] = 42 // 能改变对应的值
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
fmt.Println(e)
fmt.Printf("e Length: %v\n",len(e))
fmt.Printf("e Capacity: %v\n",cap(e))
make(Type,Length,Capacity)
a := make([]int,3)
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
a := make([]int,3,100) // make(Type,Length,Capacity)
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
append()
a := []int{}
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
// append(slice,elems)
a = append(a,1)
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
a = append(a,2,3,4,5)
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
a = append(a,[]int{2,3,4,5}...)
fmt.Println(a)
fmt.Printf("Length: %v\n",len(a))
fmt.Printf("Capacity: %v\n",cap(a))
a := []int{1,2,3,4,5}
b := a[:len(a)-1]
fmt.Println(b)
a := []int{1,2,3,4,5}
fmt.Println(a)
b := append(a[:2],a[3:]...)
fmt.Println(b)
fmt.Println(a)
// OUT PUT
[1 2 3 4 5]
[1 2 4 5]
[1 2 4 5 5]
SUMMARY
- Arrays
- Collection of items with same type
- Fixed size
- Declaration styles
- a := [3]int{1,2,3}
- a := [...]int{1,2,3}
- var a [3]int
- Access via zero-based index
- a := [3]int{1,3,5} // a[1] == 3
- len function returns size of array
- Copies refer to different underlying data
- Llices
- Backed by array
- Creation styles
- Slice existing array or slice
- Literal style
- Via make function
- a := make([]int,10) // create slice with capacity and length == 10
- a := make([]int,10,100) // slice with length == 10 and capacity == 100
- len function returns length of slice
- cap function returns length of underlying array
- append function to add elements to slice
- May cause expensive copy operation if underlying array is to small
- Copies refer to same underlying array
MAPS AND STRUCTS
AGENDA
- Maps
- What are they?
- Creating
- Manipulation
- Structs
- What are they?
- Creating
- Naming conventions 命名约定
- Embedding 镶嵌
- Tags
Maps
statePopulations := map[string]int{
"California": 39250017,
"Texas": 27862596,
"Florida": 206123876,
"New York": 19745289,
"Pennsylvania": 12802503,
"Illinois": 12801539,
"Ohio": 11614373,
}
m := map[[3]int]string{}
fmt.Println(statePopulations,m)
statePopulations := make(map[string]int)
statePopulations = map[string]int{
"California": 39250017,
"Texas": 27862596,
"Florida": 206123876,
"New York": 19745289,
"Pennsylvania": 12802503,
"Illinois": 12801539,
"Ohio": 11614373,
}
m := map[[3]int]string{}
fmt.Println(statePopulations,m)