nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

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

Open nonocast opened 2 years ago

nonocast commented 2 years ago

变量

package main

func main() {
    message := "hello world"
    println(message)
}

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
```go
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 commented 2 years ago

您好,我现在正在忙,可能无法亲自回复您的邮件。我将以最快的速度,尽快给您回复。