云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

Go语言零基础入门指南(上篇)(go语言从入门到实战)

jxf315 2025-05-02 11:11:42 教程文章 8 ℃

1. Go语言简介

Go(又称Golang)是Google开发的一种静态强类型、编译型语言,于2009年正式发布。与Python和JavaScript相比:

  • 编译型 vs 解释型:Go是编译型语言(像C++),而Python和JS是解释型语言
  • 类型系统:Go是静态类型,Python是动态类型,JS是弱类型
  • 并发模型:Go内置goroutine和channel,而Python/JS使用多线程/事件循环
  • 性能:Go性能接近C,远高于Python和JS

2. 开发环境搭建

安装Go

官网下载安装包:https://golang.org/dl/

验证安装:

go version

第一个程序:Hello World

比较三种语言的实现:

Go版本:

package main  // 声明包名

import "fmt"  // 导入标准库

func main() {  // 主函数
    fmt.Println("Hello, World!")  // 打印语句
}

Python版本:

print("Hello, World!")

JavaScript版本:

console.log("Hello, World!");

Go的特点:

  1. 必须明确包声明(package main)
  2. 必须明确导入依赖(import "fmt")
  3. 函数必须明确声明func关键字
  4. 大括号是强制的,不能省略

3. 基础语法

变量声明

Go版本:

// 显式声明
var name string = "Alice"
var age int = 25

// 类型推断
var height = 175.5  // float64
weight := 68.2      // 简短声明方式

// 多变量声明
var a, b, c = 1, 2, "three"

Python版本:

name = "Alice"
age = 25
height = 175.5
a, b, c = 1, 2, "three"

JavaScript版本:

let name = "Alice";
const age = 25;
let height = 175.5;
let [a, b, c] = [1, 2, "three"];

Go的特点:

  1. 类型可以显式声明或由编译器推断
  2. :=是声明并赋值的简短形式
  3. 变量一旦声明必须使用,否则编译错误

基本数据类型

类型

Go示例

Python对应

JS对应

整数

var x int = 42

x = 42

let x = 42

浮点数

var y float64 = 3.14

y = 3.14

let y = 3.14

布尔

var b bool = true

b = True

let b = true

字符串

var s string = "hello"

s = "hello"

let s = "hello"

Go的特殊类型:

  • rune:表示Unicode码点,相当于int32
  • byte:相当于uint8

控制结构

if-else语句

Go版本:

if age >= 18 {
    fmt.Println("Adult")
} else if age > 12 {
    fmt.Println("Teenager")
} else {
    fmt.Println("Child")
}

// 带初始化语句的if
if score := getScore(); score >= 60 {
    fmt.Println("Pass")
}

Python版本:

if age >= 18:
    print("Adult")
elif age > 12:
    print("Teenager")
else:
    print("Child")

JavaScript版本:

if (age >= 18) {
    console.log("Adult");
} else if (age > 12) {
    console.log("Teenager");
} else {
    console.log("Child");
}

Go的特点:

  1. 条件表达式不需要括号
  2. 大括号是必须的
  3. 支持在if条件前执行一个简单的语句

for循环

Go版本:

// 传统for循环
for i := 0; i < 5; i++ {
    fmt.Println(i)
}

// while风格的循环
n := 0
for n < 5 {
    fmt.Println(n)
    n++
}

// 无限循环
for {
    fmt.Println("Loop forever")
    break
}

Python版本:

# 传统for循环
for i in range(5):
    print(i)

# while循环
n = 0
while n < 5:
    print(n)
    n += 1

# 无限循环
while True:
    print("Loop forever")
    break

JavaScript版本:

// 传统for循环
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// while循环
let n = 0;
while (n < 5) {
    console.log(n);
    n++;
}

// 无限循环
while (true) {
    console.log("Loop forever");
    break;
}

Go的特点:

  1. 只有for关键字,没有while
  2. 循环条件不需要括号
  3. 初始化语句可以使用简短声明(:=)

4. 函数基础

函数定义

Go版本:

// 基本函数
func add(a int, b int) int {
    return a + b
}

// 参数类型简写
func multiply(a, b int) int {
    return a * b
}

// 多返回值
func swap(x, y string) (string, string) {
    return y, x
}

// 命名返回值
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return  // 裸返回
}

Python版本:

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

def swap(x, y):
    return y, x

def split(sum):
    x = sum * 4 // 9
    y = sum - x
    return x, y

JavaScript版本:

function add(a, b) {
    return a + b;
}

const multiply = (a, b) => a * b;

function swap(x, y) {
    return [y, x];
}

function split(sum) {
    const x = Math.floor(sum * 4 / 9);
    const y = sum - x;
    return [x, y];
}

Go的特点:

  1. 参数类型在变量名之后
  2. 返回值类型在参数列表之后
  3. 支持多返回值
  4. 可以给返回值命名,简化return语句

defer关键字

Go特有的defer语句会将函数推迟到外层函数返回之后执行:

func readFile() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()  // 确保在函数返回前关闭文件
    
    // 处理文件内容
}

相当于Python的with语句或JS的try-finally:

Python版本:

with open('file.txt') as file:
    # 处理文件内容
    pass

JavaScript版本:

let file;
try {
    file = fs.openSync('file.txt', 'r');
    // 处理文件内容
} finally {
    if (file) fs.closeSync(file);
}

Go的defer特点:

  1. 推迟的函数调用会被压入栈中,在外层函数返回时按后进先出顺序执行
  2. 常用于资源清理(文件关闭、解锁等)
  3. 参数在defer语句时求值,而非调用时

上篇介绍了Go语言的基础语法,通过对比Python和JavaScript的实现,可以帮助有其他语言基础的开发者快速理解Go的特性。接下来中篇将深入探讨Go的复合数据类型、方法和接口等核心概念。

最近发表
标签列表