1 minute read

Tags:

Go Play Gorund

Go import

  • go get <package-name>

    • 可給 import 的 package 命名!
      import (
          toml "github.com/pelletier/go-toml"
      )
    
  • go mod init name-of-the-model

    • ex:
      • go mod init github.com/yuting/exercies

      • go.mod

            module github.com/yuting/exercies
        
            go 1.14
        
            require(
                github.com/yuting/kkk `version`
                xorm.io/core `version`
            )
        
      • 要 import 資料夾下的 package

            root_dir
               |
               |__dir1
               |
               |__dir2
               |
               |--go.mod
        
                   
           import (
             "github.com/yuting/exercies/dir1"
             "github.com/yuting/exercies/dir2"
           )
                 
        

Go: init

There are times, when creating applications in Go, that you need to be able to set up some form of state on the initial startup of your program. This could involve creating connections to databases, or loading in configuration from locally stored configuration files.

When it comes to doing this in Go, this is where your init() functions come into play. In this tutorial, we’ll be looking at how you can use this init() function to achieve fame and glory, or more likely to help you to build your next Go based project.

Go: built-in

  • make function

     package main
       
     import "fmt"
       
     func main() {
     	a := make([]int, 5)
     	printSlice("a", a)
       
     	b := make([]int, 0, 5)
     	printSlice("b", b)
       
     	c := b[:2]
     	printSlice("c", c)
       
     	d := c[2:5]
     	printSlice("d", d)
     }
       
     func printSlice(s string, x []int) {
     	fmt.Printf("%s len=%d cap=%d %v\n",
     		s, len(x), cap(x), x)
     }
     /////// ANS ////////
       
     // a len=5 cap=5 [0 0 0 0 0]
     // b len=0 cap=5 []
     // c len=2 cap=5 [0 0]
     // d len=3 cap=3 [0 0 0]
    
  • append function

     package main
       
     import "fmt"
       
     func main() {
     	var s []int
     	printSlice(s)
       
     	// append works on nil slices.
     	s = append(s, 0)
     	printSlice(s)
       
     	// The slice grows as needed.
     	s = append(s, 1)
     	printSlice(s)
       
     	// We can add more than one element at a time.
     	s = append(s, 2, 3, 4)
     	printSlice(s)
     }
       
     func printSlice(s []int) {
     	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
     }
       
     ////// ANS //////
       
       
     // len=0 cap=0 []
     // len=1 cap=2 [0]
     // len=2 cap=2 [0 1]
     // len=5 cap=8 [0 1 2 3 4]
    

Tags:

Updated: