NOTE

Go Language Basics

Go keywords, data structures, functions, interfaces, packages, concurrency, reflection, errors, files, and source-code references.

Go1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Keywords

1.1. for

1.1.1. Different Forms of the for Loop

1.1.1.1. Classic for Loop
//for (init;before;after)
sum := 0
for i := 0; i < 10; i++ {
	sum += i
}
1.1.1.2. while Loop
//while(xxx)
x := 0
for x < 100 {
	fmt.Println(x)
	x = x + 1
}
1.1.1.3. Infinite Loop
//for(;;)
for {
	fmt.Println("test")
}
1.1.1.4. Enhanced for Loop

//	Iterate over arrays, slices, strings, or maps, or receive messages from a channel
oldMap := map[int]string{
	1: "a",
	2: "b",
}

newMap := make(map[int]string)
for k, v := range oldMap {
	newMap[k] = v
}
  • Note: the enhanced for loop iterates using the same address, which can cause problems under concurrency.
func TestFor(t *testing.T) {
	arrays := []uint64{1,2,4}

	for _, val := range arrays {
		fmt.Println(&val, val)
	}

}

// Output

0xc00000a310 1
0xc00000a310 2
0xc00000a310 4
  • Solution: use a local variable.
func TestFor(t *testing.T) {
	arrays := []uint64{1,2,4}

	for _, val := range arrays {
		tmpVal := val
		fmt.Println(&tmpVal, tmpVal)
	}

}

// Output
0xc00000a310 1
0xc00000a320 2
0xc00000a330 4

1.2. switch

func unhex(c byte) {
	//switch {
	//case c >= '0':
	//	fmt.Println("c>=0")
	//case c == '0':
	//	fmt.Println("c==0")
	//default:
	//	fmt.Println("c<0")
	//}

	switch c {
	case '0':
		fmt.Println("0")
	case '1', '2':
		fmt.Println("1")
		break // adding break manually is also OK; qqqqq below will not be printed
		fmt.Println("qqqqqqqqqqqqqq")
	default:
		fmt.Println("others")
	}

}

1.3. defer

defer.md

1.4. make and new

make vs new.md

2. Data Structures

2.1. string

string.md

2.2. Array

array.md

2.3. slice

slice.md

2.4. map

map.md

3. Functions

function.md

4. Interfaces

interface.md

5. Packages

package.md

6. Concurrency

concurrent.md

7. Reflection

reflection.md

8. Errors

error handling.md

9. Files

file.md

10. Source Code

How to Study Go Internals · Deep Dive into Go Go Language Design and Implementation Introduction · Advanced Go Programming

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub