当前位置:网站首页>Golang Chapter 1: Getting Started
Golang Chapter 1: Getting Started
2022-08-03 22:10:00 【Learn and know insufficient ~】
Golang概述
Golang学习方向
区块链研发工程师、Go服务器端/游戏软件工程师、Golang分布式/云计算软件工程师
Golang应用领域
- 区块链
- 后端服务器应用
- 美团后台流量支撑程序
- 仙侠道
- 云计算/云服务后台应用
- 盛大云CDN
- Cloud jingdong information push service/京东分布式文件系统
Golang安装
Golang练习
HelloWorld
新建一个文件夹ch1,创建文件helloworld.go
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
cmd运行 go run helloworld.go
或者 go build helloworld.go
生成helloworld.exe,然后运行exe亦可
其中main包用来定义一个独立的可执行程序,而不是库;同时main函数是程序开始执行的地方
命令行参数
echo1.go
在ch1下创建文件echo1.go
package main
//Import multiple packages can be used()标识列表,gofmtTool will be sorted in alphabetical order
import (
"fmt"
"os"
)
func main() {
//默认string变量是空字符串""
var s, sep string
//这里的ArgsRepresentatives from the command line to obtain the parameters of the list,i从1开始是因为Args[0]是命令本身的名字
for i := 1; i < len(os.Args); i++ {
s += sep + os.Args[i]
sep = " "
}
fmt.Println(s)
}
在cmd输入go run echo1.go 参数1 参数2 参数...
输出结果为:参数1 参数2 参数...
echo2.go
第二种形式的for循环
package main
import (
"fmt"
"os"
)
func main() {
s, sep := "", ""
//使用range遍历Args会产生两个值:Index and index corresponding element;Because they don't need index,So we can use the empty identifier_来占位
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)
}
echo3.go
Because the first twos += sep + argIs the process of continuously create newstring变量,Ongoing recycling,为了提高效率,We can use the toolsstrings的Join函数
package main
import (
"fmt"
"os"
"strings"
)
func main() {
fmt.Println(strings.Join(os.Args[1:], " "))
}
找出重复行
dup1.go
控制台输入数据,And find out the repeated part
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
//利用内置函数make定义一个key为string,value为int的map
counts := make(map[string]int)
input := bufio.NewScanner(os.Stdin)
for input.Scan() {
counts[input.Text()]++
}
//忽略input.Err()中可能的错误
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
命令行ctrl+z
回车结束输入
dup2.go
Can be read in the standard input,Also can be read from the specific file流式
模式读取输入
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
//err等于nil的时候,On behalf of the normal open file
if err != nil {
//FprintfRepresentative on the standard error stream output a message,%vOn behalf of any type of value is displayed using the default format
fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
continue
}
countLines(f, counts)
f.Close()
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s", n, line)
}
}
}
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}
dup3.go
A read the entire file input to the large block of memory,All at once divided line,And then deal with these lines
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
counts := make(map[string]int)
for _, filename := range os.Args[1:] {
//data存储的是ReadFileThe function returns can be converted to a string of bytesslice,可以被strings.Split函数分割
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "dup3: %v\n", err)
continue
}
for _, line := range strings.Split(string(data), "\n") {
counts[line]++
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
GIF动画
了解即可
lissajous.go
package main
import (
"image"
"image/color"
"image/gif"
"io"
"log"
"math"
"math/rand"
"net/http"
"os"
"time"
)
//Define the sketchpad color
var palette = []color.Color{
color.White, color.Black}
const (
whiteIndex = 0 //Drawing board in the first color
blackIndex = 1 //Under the drawing board in one color
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
if len(os.Args) > 1 && os.Args[1] == "web" {
handler := func(w http.ResponseWriter, r *http.Request) {
lissajous(w)
}
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
return
}
lissajous(os.Stdout)
}
func lissajous(out io.Writer) {
const (
cycles = 5 //完整的xThe number of oscillator change
res = 0.001 //角度分辨率
size = 100 //Image canvas contains[-size .. +size]
nframes = 64 //In the animation frames
delay = 8 //以10msAs the unit of interframe delay
)
freq := rand.Float64() * 3.0 //y振荡器的相对频率
anim := gif.GIF{
LoopCount: nframes}
phase := 0.0 //phase difference
for i := 0; i < nframes; i++ {
rect := image.Rect(0, 0, 2*size+1, 2*size+1)
img := image.NewPaletted(rect, palette)
for t := 0.0; t < cycles*2*math.Pi; t += res {
x := math.Sin(t)
y := math.Sin(t*freq + phase)
img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), blackIndex)
}
phase += 0.1
anim.Delay = append(anim.Delay, delay)
anim.Image = append(anim.Image, img)
}
gif.EncodeAll(out, &anim) //注意:忽略编码错误
}
cmd输入go build lissajous
+lissajous >out.gif
可以得到out.gif文件,或者使用go run lissajous >out.gif
获取一个URL
fetch.go
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
for _, url := range os.Args[1:] {
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
os.Exit(1)
}
fmt.Printf("%s", b)
}
}
go build fetch.go
+ fetch http://pop1.io
Get the requested page
并发获取多个URL
fetchall.go
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"time"
)
func main() {
start := time.Now()
//make创建一个string类型的管道
ch := make(chan string)
for _, url := range os.Args[1:] {
go fetch(url, ch) //启动一个goroutine
}
for range os.Args[1:] {
fmt.Println(<-ch) //从通道ch接收
}
fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}
func fetch(url string, ch chan<- string) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
ch <- fmt.Sprint(err) //发送到通道ch
return
}
nbytes, err := io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close() //Don't leak resources
if err != nil {
ch <- fmt.Sprintf("while reading %s: %v", url, err)
return
}
secs := time.Since(start).Seconds()
ch <- fmt.Sprintf("%.2fs %7d %s", secs, nbytes, url)
}
go build fetchall.go
+ fetchall https://baidu.com https://google.cn
一个Web服务器
server1.go
Design a mini echo server
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handler) //回声请求调用处理程序
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
//Handler echo requestURL r的路径部分
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "URL.path = %q\n", r.URL.Path)
}
cmd输入go run server1.go
Server will open up a
可以cmdAccess can also directly through the browser to access,Browser to access the address bar enterlocalhost:8000/hello
会输出URL.path = "/hello
server2.go
在server1On the basis of the function of the new statistical visited
package main
import (
"fmt"
"log"
"net/http"
"sync"
)
//同步锁
var mu sync.Mutex
var count int
func main() {
http.HandleFunc("/", handler) //回声请求调用处理程序
http.HandleFunc("/count", counter)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
//Handler echo requestURL r的路径部分
func handler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
count++
mu.Unlock()
fmt.Fprintf(w, "URL.path = %q\n", r.URL.Path)
}
//counterShows the number of calls so far
func counter(w http.ResponseWriter, r *http.Request) {
mu.Lock()
fmt.Fprintf(w, "Count %d\n", count)
mu.Unlock()
}
其他内容
if语句
if err := r.ParseForm();err != nil{
}
//等价于
err := r.Parseform()
if err != nil{
}
But the merge statement even short and narrowerr变量的作用域.
Switch语句
switch coinflip(){
case "heads":
heads++
case "tails":
tails++
default:
fmt.Println("landed on edge!")
}
caseStatements don't likeCThroughout the execution languages, from top to bottom(Although there is a rarely usedfallthroughStatement can rewrite this behavior)
switchStatements can also do not need the operands,它就像一个case语句列表,每条caseStatements are a Boolean expression:
func Signum(x int) int{
switch{
case x > 0:
return +1
default:
return 0
case x M 0:
return 01
}
}
这种形式称为无标签
选择,等价于switch true
type命名类型
typeStatement to the existing type named
type Point struct{
x, y int
}
var p Point
更多
指针
Method and an excuse
包
注释:不能嵌套
使用go docTools can access the document
总结
goGive me feeling is dropped a lot of content in the lesson at the same time,比如–i,指针加减.
Now syntax seems not rigorous demands very actually.
边栏推荐
猜你喜欢
Nacos配置文件管理、微服务获取Nacos配置文件
CAS:1797415-74-7_TAMRA-Azide-PEG-Biotin
中国企业构建边缘计算解决方案的最佳实践
FVCOM三维水动力、水交换、溢油物质扩散及输运数值模拟丨FVCOM模型流域、海洋水环境数值模拟方法
【MySQL进阶】数据库与表的创建和管理
FVCOM 3D Numerical Simulation of Hydrodynamics, Water Exchange, Dispersion and Transport of Oil Spills丨FVCOM Model Watershed, Numerical Simulation Method of Marine Water Environment
CAS: 1192802-98-4 _uv cracking of biotin - PEG2 - azide
CAS:908007-17-0_Biotin-azide_Biotin azide
用于流动质押和收益生成的 Web3 基础设施
从0到1看支付
随机推荐
电商数仓ODS层-----日志数据装载
距LiveVideoStackCon 2022 上海站开幕还有3天!
CAS:1260586-88-6_生物素-C5-叠氮_Biotin-C5-Azide
CAS:122567-66-2_DSPE-Biotin_DSPE-Biotin
nxp官方uboot移植到野火开发板PRO(无任何代码逻辑的修改)
Security Fundamentals 8 --- XSS
LabVIEW代码生成错误 61056
一些思考:腾讯股价为何持续都低
Kubernetes入门到精通-Operator 模式
XSS online shooting range---Warmups
Teach a Man How to Fish - How to Query the Properties of Any SAP UI5 Control by Yourself Documentation and Technical Implementation Details Demo
Pay from 0 to 1
如何基于WPF写一款数据库文档管理工具(二)
Cross-end development technical reserve record
pikachu Over permission 越权
授人以渔 - 如何自行查询任意 SAP UI5 控件属性的文档和技术实现细节试读版
2022-08-03 oracle执行慢SQL-Q17对比
用于流动质押和收益生成的 Web3 基础设施
函数,递归以及dom简单操作
384. Shuffle an Array