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 (Part 3: 快速语法) #316

Open
nonocast opened this issue Aug 7, 2022 · 1 comment
Open

学习 Go (Part 3: 快速语法) #316

nonocast opened this issue Aug 7, 2022 · 1 comment

Comments

@nonocast
Copy link
Owner

nonocast commented Aug 7, 2022

变量

  • 常量: const x int32 = 1
  • 变量: var a int32 = 1
  • 隐式变量: a := 1
  • 类型: bool, byte, intX, floatX, rune, uintptr, string, array, struct, function, interface, map, slice, channel
  • int: 这个和C一样, int/uint跟随目标平台,int8, int16, int32则是指定长度
  • 显示类型转换: int(x), byte(y)
package main

func main() {
	message := "hello world"
	println(message)
}
  • 数组
package main

func main() {
	// var numbers [3]int32 = [3]int32{7, 8, 9}
	numbers := [3]int32{7, 8, 9}

	for i, n := range numbers {
		println(i, ":", n)
	}
}

逻辑

if

package main

func main() {
	flag := true

	if flag {
		println("flag is on")
	} else {
		println("flag is off")
	}
}

for

package main

func main() {
	for i := 0; i < 5; i++ {
		println(i)
	}
}

注: 不支持++i

for..range

package main

func main() {
	x := []int32{7, 8, 9}
	for i, n := range x {
		println(i, ":", n)
	}
}

函数

func Add(x int, y int) int {
	return x + y
}

指针

package main

func main() {
	var x int32 = 7
	var p *int32 = &x // p := &x
	println(*p)
	*p = 11
	println(x)
}

结构

package main

type Book struct {
	title  string
	author string
	price  float32
}

func main() {
	book := Book{"title1", "author1", 19.9}
	println(book.title)

}

goroutine

package main

import "time"

func foo() {
	println("foo")
}

func main() {
	go foo()
	time.Sleep(1 * time.Second)
	println("end")
}

到这里其实都非常C,在C的基础上很克制的增加了高级语法。你会很清晰的知道每个点对应C的什么痛点。

最后附上一个最简单的Gin的web app,

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, "hello world")
	})

	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

go build能直接生成出单个可执行文件,没有那么多依赖,就这个比nodejs香太多了。。。

@icehoo
Copy link

icehoo commented Aug 7, 2022 via email

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

2 participants