Variables

Normal Declaration:

string msg;
msg = "Hello";

Implicit Type (var):

var msg = "Hello";
Constants
const double Phi = 1.618;
Strings
string str = "Hello";

Multiline string (verbatim)

string str = @"Multiline
string";

String interpolation

string name = "World";
string greeting = $"Hello, {name}!";
Numbers

整數 Integer

/// | `short`| 16-bit | -2¹⁵ ~ 2¹⁵-1 | -32,768 ~ 32,767 | 正負 3 萬,4 位數 |
/// | `int`  | 32-bit | -2³¹ ~ 2³¹-1 | -2.1B ~ 2.1B     | 正負 21 億,10 位數|
///| `long`  | 64-bit | -2⁶³ ~ 2⁶³-1 | -9.2E ~ 9.2E     | 正負 922 京,19 位數|
byte b = 255;
short s = 32000;
int num = 3;
long l = 100000L;

浮點 Floating

///| `float`   | 32-bit  | ±3.4×10³⁸  | ~7 位數  |
///| `double`  | 64-bit  | ±1.7×10³⁰⁸ | ~15 位數 |
///| `decimal` | 128-bit | ±7.9×10²⁸  | ~28 位數 |
float f = 3.14f;
double d = 3.14;
decimal m = 3.14m;
Arrays
// Fixed size array
int[] numbers = new int[5];

// Array with initializer
int[] numbers = { 1, 2, 3, 4, 5 };

// Multi-dimensional array
int[,] matrix = new int[3, 3];
Nullable Types
int? nullableInt = null;
nullableInt = 5;

// Null coalescing
int value = nullableInt ?? 0;

// Null conditional
string? name = null;
int? length = name?.Length;

Nullable types allow value types to represent undefined values.

List

List<T> 一維動態陣列

List<int> list = new List<int> { 1, 2, 3 };
list.Count;         // 3
list.Add(4);        // { 1, 2, 3, 4 }
list.Remove(2);     // 移除值 2,{1, 3, 4}
list.RemoveAt(2);   // 移除索引 2,{1, 3}
list.Contains(3);   // true
list.IndexOf(1);    // 0
list.Sort();
list.Reverse();

List<List<T>> 巢狀動態陣列,完全動態

List<List<int>> nested = new List<List<int>>
{
    new List<int> { 1, 2 },
    new List<int> { 3, 4, 5 }
};
nested.Add(new List<int> { 6, 7 });  // 新增一列
nested[0].Add(3);                     // 第一列加元素
nested[1][2];                         // 5
nested.Count;                         // 3
Array

Single 一維陣列,固定長度

int[] numbers = new int[5];
int[] numbers = { 1, 2, 3, 4, 5 };

Array.Sort(numbers);
Array.Reverse(numbers);
var l = numbers.Length; //5

Multi-dimensional 多維陣列,矩形固定

int[,] matrix = new int[3,4]
{
    { 1,  2,  3,  4 },
    { 5,  6,  7,  8 },
    { 9, 10, 11, 12 }
};
int val = matrix[1, 2];  // 7

Jagged 鋸齒陣列,每列可不同長,Array of Array

int[][] jagged = new int[4][] // 只能固定第一元長度
{
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 },
    new int[] { 6 }
};
int val2 = jagged[1][2];        // 5
jagged[3];                      // null
jagged[3][0];                   // NullReferenceException
jagged[3] = new int[] { 1, 2 }; // 指定位置值,不能 add
jagged.Length;                  // 4
Dictionary
Dictionary<string, int> dict = new Dictionary<string, int>
{
    { "one", 1 },
    { "two", 2 }
};
dict["three"] = 3;
var key = dict.FirstOrDefault(x => x.Value == 1).Key; // key = "one"
int val = dict["one"]; // val = 1,throws if missing
dict.TryGetValue("one", out int val); //val = 1,safe, returns bool
dict.ContainsKey("one");   // true
dict.ContainsValue(1);     // true
dict.Keys;                 // ICollection<string>
dict.Values;               // ICollection<int>
HashSet
HashSet<int> set = new HashSet<int> { 1, 2, 3 };
set.Add(4);
set.Remove(2);
set.Contains(3);           // true

Set operations

// 
HashSet<int> other = new HashSet<int> { 3, 4, 5 };
set.UnionWith(other);      // { 1, 3, 4, 5 }
set.IntersectWith(other);  // { 3, 4 }
set.ExceptWith(other);     // { 1 }
Stack (LIFO)
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
int top = stack.Pop();     // 3
int peek = stack.Peek();   // 2 (不移除)
stack.Count;               // 2
stack.Contains(1);         // true
Queue (FIFO)
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
int first = queue.Dequeue();  // 1
int peek = queue.Peek();      // 2 (不移除)
queue.Count;                  // 2
queue.Contains(3);            // true
LinkedList
LinkedList<int> linked = new LinkedList<int>();
linked.AddFirst(1);
linked.AddLast(3);
linked.AddAfter(linked.First, 2);  // 1 -> 2 -> 3
linked.Count;                      // 3
var f = linked.First;              // 1
var l = linked.Last;               // 3

linked.RemoveFirst();              // 2 -> 3
linked.RemoveLast();               // 2
SortedList / SortedDictionary

SortedList - 依 key 排序,較省記憶體

SortedList<string, int> sortedList = new SortedList<string, int>
{
    { "banana", 2 },
    { "apple", 1 }
};
// Keys: apple, banana

SortedDictionary - 依 key 排序,插入/刪除較快

SortedDictionary<string, int> sortedDict = new SortedDictionary<string, int>();
Hello World

A sample go program is show here.

package main

import "fmt"

func main() {
  message := greetMe("world")
  fmt.Println(message)
}

func greetMe(name string) string {
  return "Hello, " + name + "!"
}

Run the program as below:

$ go run hello.go
Variables

Normal Declaration:

var msg string
msg = "Hello"

Shortcut:

msg := "Hello"
Constants
const Phi = 1.618
Strings
str := "Hello"

Multiline string

str := `Multiline
string`
Numbers

Typical types

num := 3          // int
num := 3.         // float64
num := 3 + 4i     // complex128
num := byte('a')  // byte (alias for uint8)

Other Types

var u uint = 7        // uint (unsigned)
var p float32 = 22.7  // 32-bit float
Arrays
// var numbers [5]int
numbers := [...]int{0, 0, 0, 0, 0}
Pointers
func main () {
  b := *getPointer()
  fmt.Println("Value is", b)
func getPointer () (myPointer *int) {
  a := 234
  return &a
a := new(int)
*a = 234

Pointers point to a memory location of a variable. Go is fully garbage-collected.

Type Conversion
i := 2
f := float64(i)
u := uint(i)
Slice
slice := []int{2, 3, 4}
slice := []byte("Hello")
for

Basic for loop

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);  // 0, 1, 2, 3, 4
}

Reverse iteration

for (int i = 4; i >= 0; i--)
{
    Console.WriteLine(i);  // 4, 3, 2, 1, 0
}

Step increment

for (int i = 0; i < 10; i += 2)
{
    Console.WriteLine(i);  // 0, 2, 4, 6, 8
}
foreach

Iterate array

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

Iterate List

List<string> names = new List<string> { "Alice", "Bob" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

Iterate Dictionary

Dictionary<string, int> dict = new Dictionary<string, int>
{
    { "one", 1 },
    { "two", 2 }
};
foreach (KeyValuePair<string, int> kvp in dict)
{
    Console.WriteLine($"{kvp.Key}: {kvp.Value}");
}
while / do-while

while - 先判斷再執行

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);  // 0, 1, 2, 3, 4
    i++;
}

do-while - 先執行再判斷,至少執行一次

int j = 0;
do
{
    Console.WriteLine(j);  // 0, 1, 2, 3, 4
    j++;
} while (j < 5);
break / continue

break - 跳出迴圈

for (int i = 0; i < 10; i++)
{
    if (i == 5) break;
    Console.WriteLine(i);  // 0, 1, 2, 3, 4
}

continue - 跳過本次,繼續下一次

for (int i = 0; i < 5; i++)
{
    if (i == 2) continue;
    Console.WriteLine(i);  // 0, 1, 3, 4
}
Recursive

Factorial 階乘遞迴: 一般遞迴,堆疊累積

int Factorial(int n)
{
    if (n <= 1) return 1;
    return n * Factorial(n - 1);
}
// Factorial(5) = 5 * 4 * 3 * 2 * 1 = 120

Fibonacci 斐波那契數列遞迴: 值等於前兩項相加

int Fibonacci(int n)
{
    if (n <= 1) return n;
    return Fibonacci(n - 1) + Fibonacci(n - 2);
}
// Fibonacci(6) = 8  (0, 1, 1, 2, 3, 5, 8)

FactorialTail 尾遞迴: 累加器攜帶中間結果,不累積堆疊

int FactorialTail(int n, int acc = 1)
{
    if (n <= 1) return acc;
    return FactorialTail(n - 1, n * acc);
}
Condition
if day == "sunday" || day == "saturday" {
  rest()
} else if day == "monday" && isTired() {
  groan()
} else {
  work()
}
if _, err := doThing(); err != nil {
  fmt.Println("Uh oh")
Switch
switch day {
  case "sunday":
    // cases don't "fall through" by default!
    fallthrough

  case "saturday":
    rest()

  default:
    work()
}
Loop
for count := 0; count <= 10; count++ {
  fmt.Println("My counter is at", count)
}
entry := []string{"Jack","John","Jones"}
for i, val := range entry {
  fmt.Printf("At position %d, the character %s is present\n", i, val)
n := 0
x := 42
for n != x {
  n := guess()
}
Condition
if day == "sunday" || day == "saturday" {
  rest()
} else if day == "monday" && isTired() {
  groan()
} else {
  work()
}
if _, err := doThing(); err != nil {
  fmt.Println("Uh oh")
Variable
NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}
Condition
if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi