• Go for A Tour of Go 20230924 Day4


    1. package main
    2. import (
    3. "fmt"
    4. "time"
    5. )
    6. func main() {
    7. fmt.Println("Welcome to the Playground!")
    8. fmt.Println("This time is ", time.Now())
    9. }
    1. Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/TourOfGo/sandbox
    2. $ go run sandbox.go
    3. Welcome to the Playground!
    4. This time is 2023-09-23 14:58:02.4585324 +0800 CST m=+0.001689601
    5. Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/TourOfGo/sandbox
    6. $

    2.Package

    Packages

    Every Go program is made up of packages.

    Programs start running in package main.

    This program is using the packages with import paths "fmt" and "math/rand".

    1. package main
    2. import (
    3. "fmt"
    4. "math/rand"
    5. /*"crypto/rand"*/)
    6. func main() {
    7. fmt.Println("My favorite number is", rand.Intn(100))
    8. }
    1. Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/TourOfGo/Packages
    2. $ go run packages.go
    3. My favorite number is 81

    3. Imports

    This code groups the imports into a parenthesized, "factored" import statement.

    You can also write multiple import statements, like:

    import "fmt"
    import "math"

    But it is good style to use the factored import statement.

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func main() {
    7. fmt.Printf("Now you have %g problems.\n", math.Sqrt(7))
    8. }

    4.Exported names

    In Go, a name is exported if it begins with a capital letter. For example, Pizza is an exported name, as is Pi, which is exported from the math package.

    pizza and pi do not start with a capital letter, so they are not exported.

    When importing a package, you can refer only to its exported names. Any "unexported" names are not accessible from outside the package.

    Run the code. Notice the error message.

    To fix the error, rename math.pi to math.Pi and try it again.

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func main() {
    7. fmt.Println(math.Pi)
    8. }

    5.Functions

    A function can take zero or more arguments.

    In this example, add takes two parameters of type int.

    Notice that the type comes after the variable name.

    1. package main
    2. import "fmt"
    3. func add(x int, y int) int {
    4. return x + y
    5. }
    6. func main() {
    7. fmt.Println(add(42, 13))
    8. }

    6.Functions continued

    When two or more consecutive named function parameters share a type, you can omit the type from all but the last.

    In this example, we shortened

    x int, y int

    to

    x, y int
    1. package main
    2. import "fmt"
    3. func add(x, y int) int {
    4. return x + y
    5. }
    6. func main() {
    7. fmt.Println(add(42, 13))
    8. }

    7.Multiple results

    A function can return any number of results.

    The swap function returns two strings.

    1. package main
    2. import "fmt"
    3. func swap(x, y string) (string, string) {
    4. return y, x
    5. }
    6. func main() {
    7. a, b := swap("hello", "world")
    8. fmt.Println(a, b)
    9. }

    8. Named return values

    Go's return values may be named. If so, they are treated as variables defined at the top of the function.

    These names should be used to document the meaning of the return values.

    A return statement without arguments returns the named return values. This is known as a "naked" return.

    Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.

    1. package main
    2. import "fmt"
    3. func split(sum int) (x, y int) {
    4. x = sum * 4 / 9
    5. y = sum - x
    6. return
    7. }
    8. func main() {
    9. fmt.Println(split(17))
    10. }

    9.Variables

    The var statement declares a list of variables; as in function argument lists, the type is last.

    A var statement can be at package or function level. We see both in this example.

    1. package main
    2. import "fmt"
    3. var c, python, java bool
    4. func main() {
    5. var i int
    6. fmt.Println(i, c, python, java)
    7. }

    10.Variables with initializers

    A var declaration can include initializers, one per variable.

    If an initializer is present, the type can be omitted; the variable will take the type of the initializer.

    1. package main
    2. import "fmt"
    3. var i, j int = 1, 2
    4. func main() {
    5. var c, python, java = true, false, "no!"
    6. fmt.Println(i, j, c, python, java)
    7. }

    11. Short variable declarations

    Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

    Outside a function, every statement begins with a keyword (var, func, and so on) and so the := construct is not available.

    1. package main
    2. import "fmt"
    3. func main() {
    4. var i, j int = 1, 2
    5. k := 3
    6. c, python, java := true, false, "no!"
    7. fmt.Println(i, j, k, c, python, java)
    8. }

    12. Basic types

    Go's basic types are

    bool
    
    string
    
    int  int8  int16  int32  int64
    uint uint8 uint16 uint32 uint64 uintptr
    
    byte // alias for uint8
    
    rune // alias for int32
         // represents a Unicode code point
    
    float32 float64
    
    complex64 complex128

    The example shows variables of several types, and also that variable declarations may be "factored" into blocks, as with import statements.

    The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

    1. package main
    2. import (
    3. "fmt"
    4. "math/cmplx"
    5. )
    6. var (
    7. ToBe bool = false
    8. MaxInt uint64 = 1<<64 - 1
    9. z complex128 = cmplx.Sqrt(-5 + 12i)
    10. )
    11. func main() {
    12. fmt.Printf("Type: %T Vaule: %v\n", ToBe, ToBe)
    13. fmt.Printf("Type: %T Vaule: %v\n", MaxInt, MaxInt)
    14. fmt.Printf("Type: %T Vaule: %v\n", z, z)
    15. }

    13. Zero values

    Variables declared without an explicit initial value are given their zero value.

    The zero value is:

    • 0 for numeric types,
    • false for the boolean type, and
    • "" (the empty string) for strings.
    1. package main
    2. import "fmt"
    3. func main() {
    4. var i int
    5. var f float64
    6. var b bool
    7. var s string
    8. fmt.Printf("%v %v %v %q\n", i, f, b, s)
    9. }

    14.Type conversions

    The expression T(v) converts the value v to the type T.

    Some numeric conversions:

    var i int = 42
    var f float64 = float64(i)
    var u uint = uint(f)

    Or, put more simply:

    i := 42
    f := float64(i)
    u := uint(f)

    Unlike in C, in Go assignment between items of different type requires an explicit conversion. Try removing the float64 or uint conversions in the example and see what happens.

    1. package main
    2. import (
    3. "fmt"
    4. "math"
    5. )
    6. func main() {
    7. var x, y int = 3, 4
    8. var f float64 = math.Sqrt(float64(x*x + y*y))
    9. var z uint = uint(f)
    10. fmt.Println(x, y, z)
    11. }

    15.Type inference

    When declaring a variable without specifying an explicit type (either by using the := syntax or var = expression syntax), the variable's type is inferred from the value on the right hand side.

    When the right hand side of the declaration is typed, the new variable is of that same type:

    var i int
    j := i // j is an int

    But when the right hand side contains an untyped numeric constant, the new variable may be an int, float64, or complex128 depending on the precision of the constant:

    i := 42           // int
    f := 3.142        // float64
    g := 0.867 + 0.5i // complex128

    Try changing the initial value of v in the example code and observe how its type is affected.

    1. package main
    2. import "fmt"
    3. func main() {
    4. v := 42 // change me!
    5. fmt.Printf("v is of type %T\n", v)
    6. }

    16.Constants

    Constants are declared like variables, but with the const keyword.

    Constants can be character, string, boolean, or numeric values.

    Constants cannot be declared using the := syntax.

    1. package main
    2. import "fmt"
    3. const Pi = 3.14
    4. func main() {
    5. const World = "世界"
    6. fmt.Println("Hello", World)
    7. fmt.Println("Happy", Pi, "Day")
    8. const Truth = true
    9. fmt.Println("Go rules?", Truth)
    10. }

    17.Numeric Constants

    Numeric constants are high-precision values.

    An untyped constant takes the type needed by its context.

    Try printing needInt(Big) too.

    (An int can store at maximum a 64-bit integer, and sometimes less.)

    1. package main
    2. import "fmt"
    3. const (
    4. // Create a huge number by shifting a 1 bit left 100 places.
    5. // In other words, the binary number that is 1 followed by 100 zeroes.
    6. Big = 1 << 100
    7. // Shift it right again 99 places, so we end up with 1<<1, or 2.
    8. Small = Big >> 99
    9. )
    10. func needInt(x int) int { return x*10 + 1 }
    11. func needFloat(x float64) float64 {
    12. return x * 0.1
    13. }
    14. func main() {
    15. fmt.Println(needInt(Small))
    16. fmt.Println(needFloat(Small))
    17. fmt.Println(needFloat(Big))
    18. }

  • 相关阅读:
    项目中常见NPE空指针异常
    一文带你入门机器学习超参数优化算法
    Python爬虫之Js逆向案例(13)-某乎最新x-zse-96的rpc方案后续
    Windows进程的创建与结束
    【C++入门】结构体
    代码随想录算法训练营Day 52 || 300.最长递增子序列、674. 最长连续递增序列、718. 最长重复子数组
    万物皆可集成系列:低代码对接Web Service接口
    灰度图处理方法
    Python21天学习挑战赛Day(11)·爬虫入门知识(应用)
    QML使用C++model(撤销恢复)
  • 原文地址:https://blog.csdn.net/u011868279/article/details/133206697