写一个go语言的hello world

1、编写源码文件

vim first.go

package main
import (
"fmt"
)


func main(){

fmt.Println("hello world,my first go !")   #这里的P大写要注意
}

 

2、编译成二进制可执行文件

go build

 

报错1:

root@VM-0-3-debian:~/mygo# go build
go: go.mod file not found in current directory or any parent directory; see 'go help modules'

 

解决:开启go modules功能

go env -w GO111MODULE=auto 

 

报错2:

root@VM-0-3-debian:~/mygo# go build
first.go:3:7: cannot find package "fmt" in any of:
/usr/local/go/bin/src/fmt (from $GOROOT)
/root/mygo/src/fmt (from $GOPATH)
package .: cannot find package "runtime" in any of:
/usr/local/go/bin/src/runtime (from $GOROOT)
/root/mygo/src/runtime (from $GOPATH)

 

解决:请检查环境变量GOROOT是否设置对了,必须是go的安装目录,通常为 /usr/local/go

报错3:

root@VM-0-3-debian:~/mygo# go build
# _/root/mygo
./first.go:9:8: undefined: fmt.println

解决:fmt.println 改为 fmt.Println ,P是大写的。

输出正常:

root@VM-0-3-debian:~/mygo# ls -lh
total 1.7M
-rw-r--r-- 1 root root 100 May 21 21:42 first.go
-rwxr-xr-x 1 root root 1.7M May 21 21:42 mygo  ---可执行文件
drwxr-xr-x 3 root root 4.0K May 21 21:25 pkg

 

3、执行可执行文件

root@VM-0-3-debian:~/mygo# ./mygo
hello world,my first go !

 完成

4、其他编译技巧

(1)指定编译输出路径

go build  -o $dir/filename

示例:

 

 (2)指定编译的操作系统和cpu架构

GOOS=XXX GOARCH=XXX

示例:

(3)其他go支持的操作系统和cpu架构

1
2
3
4
5
6
7
8
9
10
11
12
root@VM-0-3-debian:/usr/local/go/src/go/build# cat syslist.go
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
 
package build
 
// List of past, present, and future known GOOS and GOARCH values.
// Do not remove from this list, as these are used for go/build filename matching.
 
const goosList = "aix android darwin dragonfly freebsd hurd illumos ios js linux nacl netbsd openbsd plan9 solaris windows zos "
const goarchList = "386 amd64 amd64p32 arm armbe arm64 arm64be loong64 mips mipsle mips64 mips64le mips64p32 mips64p32le ppc ppc64 ppc64le riscv riscv64 s390 s390x sparc sparc64 wasm "

  

 

posted @   格林兰岛  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示