Golang基础学习

💡 Golang Tutorial for Beginners | Full Go Course

基本结构

  1. 创建文件夹

  2. 创建main.go

  3. 执行命令,生成 go.mod 文件

    go mod init 文件夹名
    
  4. 在 main.go 中输入如下代码,运行成功

    package main
    
    import "fmt"
    
    func main() {
    	fmt.Print("Hello World")
    }
    

    注意:不使用的package不要import

优点

  1. Discover mistakes at compile time, NOT at runtime

Variables & Constants

Variables

  1. 变量的声明

    var name = "Go Conference"
    name := "Go Conference"
    
  2. 注意事项:

    1. 声明的变量必须使用,否则就不要声明变量
    var conferenceName = "Go Conference"
    
    fmt.Println("Welcome to", conferenceName, "booking application")
    

Constants

与变量(Variables)类似,但值无法改变

// 使用 const 声明
const conferenceTickets = 50

Package Level Variables

  • Defined at the top outside of all functions - 在main函数以外上面定义
  • They can be accessed inside any of the functions
  • And in all files, which are in the same package
  • 不能用 := 创建
  • 传参时不用写

Local Variables

  • Defined inside a function or a block
  • They can be accessed only inside that function or block of code
  • Create the variable where you need it

Formatted Output

Print formatted data

fmt.Printf("some text with a variable %s", myVariable

Data Types

声明类型

// var something Type
var userName string

检查类型

// 用 %T
fmt.Printf(%T, something)
  • The type keyword creates a new type, with the name you specify
  • In fact, you could also create a type based on every other data type like int, string etc.
type
type name struct
type name int
type name string

Strings & Integers & Booleans

  • Strings : for textual data, defined with double quotes, eg : “This is a string”
  • Integers : representing whole numbers, positive and negative, eg : 5, 10, -20

在这里插入图片描述

```go
// 数字42转字符串,依旧是十进制形式,若为16,则是16进制
strconv.FormatUint(uint64(42), 10) // 42, string
strconv.FormatUint(uint64(42), 16) // 2a, string
```
  • Booleans : True or False
var noSomething bool = something == 0
noSomething := something == 0

Maps

  • Maps unique keys to values
  • You can retrieve the value by using its key later
  • All keys have the same data type
  • All values have the same data type
var myMap = make(map[keyType]valueType)

// example
var userData = make(map[string]string)
userData["firstName"] = firstName

Arrays & Slices

  • Arrays

    • 必须知道大小
    • Fixed Size
    • Only the same data type can be stored
    var bookings = [50]string{"A", "B", "C"}
    
    var bookings [50]string
    bookings[0] = "Text"
    bookings[1] = first + " " + last
    
    // Arrays的大小
    len(array)
    
  • Slices

    • 大小可变
    • Slice is an abstraction of an Array
    • More flexible and powerful : variable-length or an sub-array of its own
    • Slices are also index-based and have a size, but is resized when needed
    // 声明方式
    var bookings []string
    
    bookings := []string{}
    
    sliceName = append(sliceName, elements)   // Adds the element(s) at the end of the slice.
    
    • Creating a slice with make()

      • Alternative way to create a slice
      • We need to define the initial size of the slice
      var bookings = make([]map[string]string, 0)
      

Structs

  • Collect different data types of data
  • type statement - Custom Types
    • The type keyword creates a new type, with the name you specify
    • “create a type called “userData” based on a struct of firstName, lastName…”
  • Defining a structure
    • Mixed data type
    • Defining a structure (which fields) of the User Type
  • It’s like a lightweight class, which e.g. doesn’t support inheritance
// 创建struct
type UserData struct {
	firstName       string
	numberOfTickets uint
}

// 赋值
var userData = UserData{
		firstName:       firstName,
		numberOfTickets: userTickets,
}

// 使用
userData.firstName
userData.numberOfTickets

User Input

// Scan() 括号里要么是指针,要么是具体地址
fmt.Scan(&inputText)
fmt.Scan(0xc00124)

user input validation

Pointers

  • A pointer is a variable that points to the memory address of another variable.
  • A special variable.

请添加图片描述

Scope Rules

Variable Scopes

Scope is the region of a program, where a defined variable can be accessed

3 Levels of Scope

  • Local
    • Declaration within function
      • Can be used only within that function
    • Declaration within block (eg. for, if-else)
      • Can be used only within that block
  • Package
    • Declaration outside all functions
      • Can be used everywhere in the same package
  • Global
    • Declaration outside all functions & uppercase first letter
      • Can be used everywhere across all packages

Loops

  • Only have the “for loop”
  • Infinite Loop
for {
	
}

// 用户使用 ctrl + C 退出循环

// 本质是

for true {

}
  • For-Each Loop : Iterating over a list
// Range iterates over elements for different data structures (so not only arrays and slices)
// For arrays and slices, range provides the index and value for each element
for condition {
		
}

// 遍历完bookings里面所有元素后结束循环

for index, booking := range bookings {
		var names = strings.Fields(booking)
		firstNames = append(firstNames, names[0])
}

// 用不到index可以用下划线代替

for _, booking := range bookings {
}
  • 使用break退出循环
  • 使用continue继续

If-else & Switch

if-else

if condition {
		// code to be executed if condition is true
} else if condition {
		// code to be executed if condition is true
} else {
		// code to be executed if both conditions are false
}

// 可以没有else, else if 
// else if 可以有多个,else 只能有一个

switch

Allows a variable to be tested for equality against a list of values

// Example

text := "B"
switch text {
		case "A":
				// some code here
		case "B":
				// some code here
		case "C", "D":
				// same code here for C and D
		default:
				// some code here
				// Default handles the case, if no match is found
}

Functions

  • Encapsulate code into own container (= function). Which logically belong together!
  • Like variable name, you should give a function a descriptive name
  • Call the function by its name, whenever you want to execute this block of code
  • Every program has at least one function, which is the main() function
  • Function is only executed, when “called” !
func functionName(parameters and parametersType) (returnType){
		// function body
		// Encapsulate code
		fmt.Println("hello")
}
  • Function Parameters
    • Information can be passed into functions as parameters
    • Parameters are also called arguments
  • Returning values from a function
    • A function can return data as a result
    • So a function can take an input and return an output
    • In Go you have to define the input and output parameters including its type explicitly
    • Returning multiple values

Packages

  • Go programs are organized into packages
  • A package is a collection of Go files
  • 如果全在一个package,运行时在包含所有go文件的文件夹终端输入go run .
    在这里插入图片描述在这里插入图片描述在这里插入图片描述

Multiple Package

go.mod

module booking-app = import path

For all our packages in our booking-app application

Import package

  • Exporting a variable
    • Make it available for all packages in the app
    • Capitalize first letter - 首字母大写

Goroutines 协程,并发编程

  • go … starts a new goroutine // 让它多进程同时运行(?)
  • A goroutine is a lightweight thread managed by the Go runtime
  • Waitgroup
    • Waits for the lunched goroutine to finish
    • Package “sync” provides basic synchronization functionality
    • Add() Sets the number of goroutine to wait for (increases the counter by the provided number)
    • Wait() Blocks until the WaitGroup counter is 0
    • Done() Decrements the WaitGroup counter by 1. So this is called by the goroutine to indicate that it’s finished
var wg = sync.WaitGroup{}
wg.Add(1)  // 为 wg 添加一个计数
wg.Wait()  // 等待所有的协程执行结束
wg.Done()  // 减去一个计数

  • Managed by the go runtime, we are only interacting with these high level goroutines
  • Cheaper & lightweight
  • You can run hundreds of thousands or millions goroutines without affecting the performance

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值