Go Programming Language Notes

website·Indexed 31 days ago

https://0x0bit.github.io

A collection of technical notes and tutorials on the Go programming language, covering installation, variable declaration, built-in variables, constants, and the use of the rune type for string traversal.

Tokens
2K
Snippets
15
Records
20
Agent score
75%

What's inside Go

  1. Understand and use the rune type in Go

    In Go, a rune is a 32-bit integer type that represents a single Unicode code point, effectively serving as the char type found in other languages. It is used to handle multi-byte characters (like Chinese characters) correctly, as standard strings in Go are sequences of bytes.
  2. Declare variables using the var keyword in Go

    In Go, variables are declared using the var keyword with the syntax var identifier type. Unlike C, the type follows the identifier to avoid ambiguity and improve readability. Multiple variables of the same type can be declared in a single line, or grouped using a factored block, which is commonly used for global variables.
    // Individual declarations
    var a int
    var b bool
    var str string
    
    // Multiple variables of the same type
    var a, b *int
    
    // Factored block (common for global variables)
    var (
        a int
        b bool
        str string
    )
  3. Define constants in Go

    Constants are identifiers for simple values that cannot be modified during program execution. In Go, constants can only be of the following data types: boolean, numeric (integer, floating-point, complex), and string. The general definition format is const identifier [type] = value.
    const fileName = "abc.txt"
    const a, b = 3, 4
  4. Create enumerations using iota

    The iota identifier is a constant counter used to simplify the definition of incrementing values. It starts at 0 and increments by 1 for each subsequent line in a constant block. You can skip values by using the blank identifier _ or perform arithmetic operations with iota to create seeds for values (e.g., calculating memory units).
    const (
        cpp = iota // 0
        java       // 1
        python     // 2
        golang     // 3
    )
    
    // Skipping a value
    const (
        a = iota // 0
        _        // 1 (skipped)
        b        // 2
    )
    
    // Using iota for memory units (1 << (10 * iota))
    const (
        _ = iota
        KB = 1 << (10 * iota) // 1024
        MB = 1 << (10 * iota) // 1048576
    )
  5. Manage constant scope and grouped declarations

    Constants can be defined inside a function (local scope) or outside a function (global scope). When defining multiple constants, you can use a factored block const (...) to group them for better readability.
    // Grouped declaration
    const (
        fileName = "abc.txt"
        d, f     = 3, 4
    )
  6. Configure VS Code for Go development

    To set up VS Code for Go, install the official Go extension. If the 'Install All' prompt for Go tools fails, manually clone the required tools into the $GOPATH/src/golang.org/x directory before running the update command in VS Code.

    1. Create the directory structure: $GOPATH/src/golang.org/x.
    2. Clone the tools into that directory.
    3. In VS Code, open the Command Palette (Cmd+Shift+P), run Go: Install/Update Tools, select all tools, and confirm.
    # Navigate to the x directory within GOPATH/src
    mkdir -p $GOPATH/src/golang.org/x
    cd $GOPATH/src/golang.org/x
    
    # Clone the necessary tools
    git clone https://github.com/golang/tools.git tools
    git clone https://github.com/golang/lint.git
  7. Use short variable declarations with the := operator

    Inside functions, the := operator provides a shorthand for declaring and initializing variables without using the var keyword.

    Constraints:

    • It can only be used for the first initialization of a variable.
    • It cannot be used for re-assignment.
    • It cannot be used for variable declarations outside of functions (global scope); var must be used instead.
    func variableTypeDeduction() {
        // Short declaration (only inside functions)
        a, b, c, d := 2, 2.3, true, "def"
        fmt.Println(a, b, c, d)
    }
  8. Verify Go installation

    After configuring the environment variables, verify that Go is installed correctly by running the go env command in the terminal. A successful installation will output the current Go environment configuration.
    go env
  9. Apply Go variable naming and visibility rules

    Go uses camelCase for variable naming (e.g., numShips, startDate).

    Visibility/Export rules:

    • Internal/Private: Start the first word with a lowercase letter.
    • External/Public: Start the first word with an uppercase letter to make the variable accessible to external packages.
  10. Iterate over a string by character using rune

    To iterate over a string character-by-character (handling multi-byte Unicode characters as single units), convert the string to a []rune slice. Iterating over a []byte slice will instead yield the individual bytes of the UTF-8 encoding.
    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func main()  {
        s := "Yes我爱大中国"
        
        // Iterating by byte: yields UTF-8 byte values
        for _, b := range []byte(s){
            fmt.Printf("%X \n", b)
        }
        
        // Get actual character count (Unicode code points)
        fmt.Println("字符数:", utf8.RuneCountInString(s))  // 8
        
        // Iterating by rune: yields actual characters
        for i, ch := range []rune(s){
            fmt.Printf("(%d, %c) \n", i, ch)  // (0, Y)(1, e)(2, s)(3, 我)(4, 爱)(5, 大)(6, 中)(7, 国)
        }
    }
  11. Initialize variables with type inference

    Go can automatically infer a variable's type based on the assigned value. However, if a specific type is required (e.g., int64 instead of the default int), the type must be explicitly declared.
    // Type inference
    var a, b, c, d = 2, 2.3, true, "def"
    var e = 15
    
    // Explicit type required for specific precision/type
    var n int64 = 2
  12. Configure Go environment variables on macOS/Linux

    To complete the Go installation, you must configure the GOROOT, GOPATH, and PATH environment variables in your shell profile (e.g., .bash_profile). GOROOT points to the Go installation directory, and GOPATH points to your workspace directory where your code and downloaded packages reside.
    export GOROOT=/usr/local/opt/go/libexec
    export GOPATH=/Users/deweixu/coding/Go/go_path
    export PATH=$PATH:$GOROOT/bin:$GOPATH/bin