Preface
When learning a language, it's hard to avoid learning from the simplest program structure. When mastering another development language (such as the famous java), these things will look like a fish in water. I'll share some simple examples below.
Basic program structure
Quickly assign values to some variables
const ( NUM1 = 1 + iota NUM2 NUM3 NUM4 ) //Output: 1, 2, 4, 8 func TestPrint(t *testing.T) { t.Log(NUM1, NUM2, NUM3, NUM4) }
Fast implementation of some numerical exchange
//Numerical exchange func TestExchange(t *testing.T) { //You can also define variables like this: var aa int = 1 a := 1 b := 2 t.Log(a, b) //Exchange value b, a = a, b t.Log(a, b) }
Type conversion
//Name the type type typeInt int64 func TestInt(t *testing.T) { var a int64 = 2 var b int32 = 3 //Type cannot be transferred //a = b var c = typeInt(3) t.Log(a, b, c) }
Two ways to realize fibolacci sequence
//Fei Po La Chi func TestFibList(t *testing.T) { var a int = 1 var b int = 1 t.Log(a) for i := 0; i < 5; i++ { t.Log(b) tmp := a + b a = b b = tmp } } //Fibolacci recursion func TestFibRecursion(t *testing.T) { t.Log(FibRecursion(5)) } func FibRecursion(i int) (result int) { if i == 1 || i == 2 { return 1 } return FibRecursion(i-1) + FibRecursion(i-2) }
Array comparison, different from java, is not a comparison pointer, which can compare values
//Array comparison func TestCompareArray(t *testing.T) { a := [...]int{1, 2, 3, 4} b := [...]int{1, 2, 2, 4} c := [...]int{1, 2, 3, 4} t.Log(a == b) //false t.Log(a == c) //true }
go also has a pointer, but I didn't look at it carefully. I just wrote an example to see the result
func TestPoint(t *testing.T) { var a int64 = 1 var aPtr = &a t.Log(a, aPtr)// 1 0xc420018230 //Printing class: int64 *int64 t.Logf("%T %T", a, aPtr) }
Default value of string
func TestString(t *testing.T) { //The default value is not java null var str string t.Log("+" + str + "+")//Output + + }
for cycle
//There was no while in the for loop go func TestFor(t *testing.T) { n := 5 for n > 0 { t.Log(n) n-- } } //For loop for bubble sorting func TestForSort(t *testing.T) { a := [...]int{3, 5, 2, 6, 4, 8, 2, 9,1,23,2,34,4,55,11} for i := 0; i < len(a)-1; i++ { for j := 0; j < len(a)-i-1; j++ { if a[j] > a[j+1] { tmp := a[j] a[j] = a[j+1] a[j+1] = tmp } } } t.Log(a)//[1 2 2 2 3 4 4 5 6 8 9 11 23 34 55] }
The condition judgment in go is very good
//compare func TestCondition(t *testing.T){ //You can assign conditional results to variables if a:=3>2;a{ t.Log("3>2") } // GOOS is the running program's operating system target: // one of darwin, freebsd, linux, and so on. switch runtime.GOOS{ //Bring break case "darwin": t.Log("darwin") case "freebsd": t.Log("freebsd") case "linux": t.Log("linux") default: t.Log("default") } switch { case 4>2: t.Log("4>2") case 4<2: t.Log("4<2") } }