0
点赞
收藏
分享

微信扫一扫

golang 系列教程

booksmg2014 2022-04-30 阅读 65

golang 系列教程

第一章 Go的Hello World


文章目录


前言

本系列文章是在学习golang官网的过程的记录,以及学习过程的想法
环境为Linux


一、创建golang项目目录

mkdir hello
cd hello

二、代码的依赖追踪(自己模块的建立)

当你的代码import的package被包含在其他的module中时,你就需要用你自己的module来管理这些依赖。
我们的module被定义在go.mod这个文件里,这个文件就是来追踪我们import的package的module的。
总的来说就是,用我们的go.mod来追踪我们import的package的module。

go mod init yourModulePath

上面说的路径,一般来说指的是源代码的仓库路径。代码一般来说放在GitHub上的,所以格式就是github.com/yourRepository。如果你想要发布你的module,你必须要能被Go的工具定位到。这就是后话了。

2.打印Hello World

package main	//声明一个main package
				//package用于对函数的功能分组,一个包所有的文件都在一个目录下

import "fmt"

func main() {	//当我们运行main package时,main()函数是被默认执行的
    fmt.Println("Hello, World!")
}
go run hello.go

三、调用非标准库的package

刚才调用的fmt是属于标准库的package,在配置好golang后就可以直接import。
当调用了非标准库,如"github.com/vova616/screenshot",这是个桌面截屏的库

package main

import (
	"image/png"
	"os"

	"github.com/vova616/screenshot"		//桌面截屏的库
)

func main() {
	//img, _ := screenshot.CaptureScreen()
	img, err := screenshot.CaptureScreen()
	if err != nil {
		panic(err)
	}
	f, err := os.Create("./ss.png")
	if err != nil {
		panic(err)
	}
	err = png.Encode(f, img)
	if err != nil {
		panic(err)
	}
	f.Close()
	
}
go mod tidy
$ go help mod
Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.

Usage:

        go mod <command> [arguments]

The commands are:

        download    download modules to local cache
        edit        edit go.mod from tools or scripts
        graph       print module requirement graph
        init        initialize new module in current directory
        tidy        add missing and remove unused modules		//可以直接帮我们添加或者删除
        vendor      make vendored copy of dependencies
        verify      verify dependencies have expected content
        why         explain why packages or modules are needed

Use "go help mod <command>" for more information about a command.
go run hello.go

目前这个库在我的环境里运行会有些bug,等好了在重新更新


总结

这节主要问题还是在module管理上。

举报

相关推荐

0 条评论