opskumu / issues

利用 issues 管理技术 tips
https://github.com/opskumu/issues/issues
80 stars 5 forks source link

go programming language #14

Closed opskumu closed 5 years ago

opskumu commented 7 years ago

《go programming language》笔记摘要

二、程序结构

命名

声明

opskumu commented 7 years ago

三、基础数据类型

字符串

In Go, a string is in effect a read-only slice of bytes.

const s = "世界"
fmt.Println(len(s))            // 输出结果为 6 表示字符串 s 占用 6 个字节,一个中文占用 3 个字节
fmt.Println(len([]rune(s)))    // 输出结果为 2 表示字符串 s 转换成 rune 之后占用 2 个 rune 字符码
const s = "世界"
for i, v := range s {
        fmt.Printf("%#U starts at byte position %d\n", v, i)
}

%#U, which shows the code point's Unicode value and its printed representation.

运行结果

U+4E16 '世' starts at byte position 0
U+754C '界' starts at byte position 3
opskumu commented 7 years ago

四、复合数据类型

数组

q := [...]int{1, 2, 3}
symbol := [...]string{0: "$", 3: "¥"}    // 数组中指定了第一个和第四个索引值,未指定的自动取空字符串

切片

package main

import "fmt"

func array(a [4]string) [4]string {
    a[0] = "That"
    return a
}

func slice(s []string) []string {
    s[0] = "That"
    return s
}

func main() {
    a := [4]string{"This", "is", "a", "test"}
    s := []string{"This", "is", "a", "test"}

    array(a)
    slice(s)
    fmt.Println(a) // 作用域问题,此处数组不会改变
    fmt.Println(s) // 因为 slice 元素本身是指针,所以此处 “This” 会被替换成 "That"
}

输出结果:

[This is a test]
[That is a test]

Map

结构体

type Circle struct {
    Point
    Radius int
}

type Wheel struct {
    Circle
    Spokes int
}

得意于匿名嵌入的特性,我们可以直接访问叶子属性而不需要给出完整的路径:

var w Wheel w.X = 8
w.Y = 8 w.Radius = 5 w.Spokes = 20
// equivalent to w.Circle.Point.X = 8
// equivalent to w.Circle.Point.Y = 8
// equivalent to w.Circle.Radius = 5
w = Wheel{Circle{Point{8, 8}, 5}, 20}

w = Wheel{
    Circle: Circle{
        Point:  Point{X: 8, Y: 8},
        Radius: 5,
    },
    Spokes: 20, // NOTE: trailing comma necessary here (and at Radius) }
fmt.Printf("%#v\n", w)
// Output:
// Wheel{Circle:Circle{Point:Point{X:8, Y:8}, Radius:5}, Spokes:20}
opskumu commented 7 years ago

五、函数

可变函数

func f(...int) {}
func g([]int) {}
fmt.Printf("%T\n", f) // "func(...int)"
fmt.Printf("%T\n", g) // "func([]int)"
opskumu commented 7 years ago

六、方法

封装

opskumu commented 7 years ago

七、接口

opskumu commented 7 years ago

八、Goroutines 和 Channel

使用内置的 make 函数,我们可以创建一个 channel:

ch := make(chan int) // ch has type 'chan int'

关于性能问题还需要进一步理解!!!

opskumu commented 7 years ago

十、包和工具

import _ "image/png" // register PNG decoder