[Day 4] -『 GO语言学习笔记』- GO语言架构介绍

如本日主题,今天要来介绍一下Go语言的程序码架构,以下内容摘录自『 The Go Workshop 』。

package main ...................................................Part 1

import (........................................................Part 2
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strconv"
	"time"
)

var helloList = []string{.......................................Part 3
	"Hello, world",
	"Καλημέρα κόσμε",
	"こんにちは世界",
	" ایند مالس",
	"Привет, мир",
}

func main() {...................................................Part 4
	rand.Seed(time.Now().UnixNano())
	index := rand.Intn(len(helloList))
	msg, err := hello(index)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(msg)
}

func hello(index int) (string, error) {.........................Part 5
	if index < 0 || index > len(helloList)-1 {
		return "", errors.New("out of range: " + strconv.Itoa(index))
	}
	return helloList[index], nil
}

Part 1

package main
  • 宣告套件(Package),所有的Go语言档案(.go)都必须以套件宣告起头。
  • 位於同一个目录下的Go语言档案,都会被视为相同套件的一部分,也就是说所有的档案开头都必须设定为相同的套件名称。

Part 2

import (
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strconv"
	"time"
)
  • 程序码汇入所需的套件。

Part 3

var helloList = []string{
	"Hello, world",
	"Καλημέρα κόσμε",
	"こんにちは世界",
	" ایند مالس",
	"Привет, мир",
}
  • 变数宣告,以上范例宣告全域变数并使用切片(slice)赋值。(後续会介绍到Go语言的三种集合:切片(slice)、阵列(array),映射表(map))

Part 4

func main() {
	rand.Seed(time.Now().UnixNano())
	index := rand.Intn(len(helloList))
	msg, err := hello(index)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(msg)
}
  • Go语言宣告的函式(function),main()为程序码的进入点。

Part 5

func hello(index int) (string, error) {
	if index < 0 || index > len(helloList)-1 {
		return "", errors.New("out of range: " + strconv.Itoa(index))
	}
	return helloList[index], nil
}
  • 自定义的函式,本范例为hello(),可接收一个为int型别的整数当参数,然後回传一个字串(string)和一个错误(error)。

<<:  Day 06:Angular 的主要特色与优点简介

>>:  【Day6】 Introduction

《赖田捕手:追加篇》第 35 天:制造 Deploy to Heroku 按钮

第 35 天:制造 Deploy to Heroku 按钮 我打开信封,有张明信片在里面。明信片封面...

想当软件工程师

请问有没有人跟我一样,没有念大学,想成为软件工程师 ...

如果你对Microsoft 认证感兴趣

首先感谢这个技术平台让我分享一些专业的东西,今天我会分享一些Microsoft exam certi...

django新手村7-----template 常用特殊标签

forloop.counter0 记数器从0开使 forloop.counter 从1开始 divi...

Day 7:持续拆解主类别

上一篇漏掉了一个主类别的函数: void anotherInstanceStarted (const...