Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GO的基础了解 (2023-09-04) #47

Open
yaogengzhu opened this issue Sep 4, 2023 · 9 comments
Open

GO的基础了解 (2023-09-04) #47

yaogengzhu opened this issue Sep 4, 2023 · 9 comments

Comments

@yaogengzhu
Copy link
Owner

如何创建一个GO的模块化

create a module

mkdir greetings

cd greetings

go mod init example.com/greetings

# 执行上面三个步骤,完成初始化,然后可以新建一个  greetings.go 文件

编写 hello.go

package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

Call your code from another module

// 在同级目录下执行
cd ..
mkdir hello
cd hello 

go mod init example.com/hello

// 初始化完成后,开始编写 hello.go


```go
package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

完成以上步骤后:需要在执行以下动作

  • 切换到hello 目录,执行如下命令

     go mod edit -replace example.com/greetings=../greetings
     go mod tidy
  • 最后可以直接运行了, go run hello.go

@yaogengzhu
Copy link
Owner Author

推荐地鼠文档: https://www.topgoer.cn/

@yaogengzhu
Copy link
Owner Author

go 拿到输入, 以及数据转换

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	println("Enter your like number: ")
	input, _ := reader.ReadString('\n')

	// 输入数据转换
	nums, err := strconv.ParseInt(strings.TrimSpace(input), 10, 64)

	if err != nil {
		fmt.Println("Error: ", err)
		return
	}
	println(nums + 1)
}

@yaogengzhu
Copy link
Owner Author

go 有意思的循环 loop

package main

import "fmt"

func main() {
	// fn1()
	// fn2()

	fn3()
}

func fn1() {
	list := []int{1, 2, 3, 4, 5}

	for key, value := range list {
		fmt.Println(key, value)
	}
}

func fn2() {
	list := []int{1, 2, 3, 4, 5}

	for i := 0; i < len(list); i++ {
		fmt.Println(i, list[i])
	}
}

// while
func fn3() {
	list := []int{1, 2, 3, 4, 5}

	i := 0
	for i < len(list) {
		if i == 3 {
			goto lco
		}
		fmt.Println(i, list[i])
		i++
	}
	// goto 语句
lco:
	fmt.Println("lco")
}

尽量避免使用GOTO 语法

@yaogengzhu
Copy link
Owner Author

GO 的文件读写

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	context := " I am a test string"

	file, err := os.Create("./test.txt")

	if err != nil {
		panic(err)
	}

	length, err := io.WriteString(file, context)
	if err != nil {
		panic(err)
	}

	println("write length:", length)
	defer file.Close()

	readFile("./test.txt")
}

func readFile(filename string) {
	file, err := os.ReadFile(filename)

	if err != nil {
		panic(err)
	}
	fmt.Println(string(file))
}

@yaogengzhu
Copy link
Owner Author

GO 语言的解析URL 参数

package main

import (
	"fmt"
	"net/url"
)

var rawURL string = "https://www.baidu.com/?name=abc&age=18"

func main() {
	reuslt, err := url.Parse(rawURL)
	if err != nil {
		panic(err)
	}

	fmt.Println(reuslt.Scheme)
	fmt.Println(reuslt.Port())
	fmt.Println(reuslt.Hostname())
	fmt.Println(reuslt.Query())

	query := reuslt.Query()

	for _, val := range query {
		fmt.Println(val)
	}
}

@yaogengzhu
Copy link
Owner Author

go 的泛型

package main

import "fmt"

func main() {
	sum := sumInt(map[int]int{1: 1, 2: 2, 3: 3})
	sum1 := sumFloats(map[string]float64{"a": 1.1, "b": 2.2, "c": 3.3})
	// print(sum)
	sum2 := SumIntsOrFloats(map[int]int{1: 1, 2: 2, 3: 3})
	sum3 := SumIntsOrFloats(map[string]float64{"a": 1.1, "b": 2.2, "c": 3.3})
	fmt.Println(sum)
	fmt.Println(sum1)
	fmt.Println(sum2)
	fmt.Println(sum3)
}

func sumInt(m map[int]int) int {
	sum := 0
	for _, v := range m {
		sum += v
	}
	return sum
}

func sumFloats(m map[string]float64) float64 {
	sum := 0.0
	for _, v := range m {
		sum += v
	}
	return sum
}

// 定义泛型
type Number interface {
	int | float64
}

func SumIntsOrFloats[K comparable, V Number](m map[K]V) V {
	var s V
	for _, v := range m {
		s += v
	}
	return s
}

@yaogengzhu
Copy link
Owner Author

GO 中的Reflect 反射 和 tag 标签

package main

import "reflect"

func main() {
	var user User

	getUserReflct(&user)
}

type User struct {
	Name string `json:"name" doc:"姓名"`
	Age  int    `json:"age" doc:"年龄"`
}

func getUserReflct(str interface{}) {

	t := reflect.TypeOf(str).Elem()

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		println(field.Tag.Get("json"))
		println(field.Tag.Get("doc"))
	}
}

@yaogengzhu
Copy link
Owner Author

GO的并发控制

package main

import (
	"fmt"
	"runtime"
	"time"
)

func Gotest() {
	i := 0
	for {
		fmt.Println("Hello World", i)
		i++
		time.Sleep(time.Second)
	}
}

func main() {
	go func() {
		defer fmt.Println("hello world End")
		fmt.Println("hello world")
		func() {
			fmt.Println("hello world 2")
			runtime.Goexit()
		}()
	}()

	i := 0
	for {
		fmt.Println("Hello World", i)
		i++
		time.Sleep(time.Second)
	}
}


@yaogengzhu
Copy link
Owner Author

yaogengzhu commented Nov 9, 2023

了解GO的channel

无缓冲的channel

package main

import "fmt"

func main() {
	// 创建一个无缓冲的channel
	c := make(chan int)
	go func() {
		// 往channel中写入数据
		c <- 42
	}()
	// 从channel中读取数据
	num := <-c
	// channel的读写都是阻塞的,所以这里会输出42
	fmt.Println(num)
}

有缓冲的channel

package main

import (
	"fmt"
	"time"
)

func main() {
	c := make(chan int, 3) // 有缓冲的channel
	go func() {
		for i := 0; i < 10; i++ {
			fmt.Println("send:", i)
			c <- i
		}
	}()

	time.Sleep(2 * time.Second)

	for i := 0; i < 10; i++ {
		println(<-c)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant