Go 知识点
定义变量自动赋类型
var v1 int
var v2 string
var v3 [10]int // 数组
var v4 []int // 数组切片
var v5 struct {
f int
}
var v6 *int // 指针
var v7 map[string]int // map,key为string类型,value为int类型
var v8 func(a int) int
v_name := value
name, age := "naveen", 29 // 简短声明
字符串和数字相互转化
//字符串转数字,要做错误处理
start, err := strconv.Atoi(page)
if err != nil {
return
}
end, err := strconv.Atoi(size)
if err != nil {
return
}
//数字转字符串
//page_start := strconv.Itoa(start)
//page_end := strconv.Itoa(end)
循环
numbers := [6]int{1, 2, 3, 5}
/* for 循环 */
for a := 0; a < 10; a++ {
fmt.Printf("a 的值为: %d\n", a)
}
for a < b {
a++
fmt.Printf("a 的值为: %d\n", a)
}
for i,x:= range numbers {
fmt.Printf("第 %d 位 x 的值 = %d\n", i,x)
函数
func cal(price, num int) int {
total := price * num
return total
}
func rectProps(length, width float64)(area, perimeter float64) {
area = length * width
perimeter = (length + width) * 2
return // 不需要明确指定返回值,默认返回 area, perimeter 的值
}
空白符
_ 代替未用到的变量
area, _ := rectProps(10.8, 5.6)
if else
if condition {
} else if condition {
} else {
}
### 常量 const
switch case
finger := 4
switch finger {
case 1:
fmt.Println("Thumb")
fallthrough //继续执行case
case finger >= 2:
fmt.Println("Index")
case finger >= 2:
fmt.Println("Index")
default:
fmt.Println("Defalut")
数组 [n]T
Go 语言中不允许混合不同类型的元素
interface{} 类型数组,可以包含任意类型
var a [3]int
a := [3]int{12, 78, 50}
a := [3]int{12}
num := [...]int{5, 6, 7, 8, 8}
for i, v := range a {//range returns both the index and value //_,v
fmt.Printf("%d the element of a is %.2f\n", i, v)
sum += v
多维数组
a := [3][2]string{
{"lion", "tiger"},
{"cat", "dog"},
{"pigeon", "peacock"}, // this comma is necessary. The compiler will complain if you omit this comma
}
切片
fruitslice := fruitarray[1:3]
//make切片
i := make([]int, 5, 5)
//添加
car = append(car,"Toyata")
### 长度和容量
len(cars) 和 cap(cars)
### 数组相加
veggies := []string{"potatoes", "tomatoes", "brinjal"}
fruits := []string{"oranges", "apples"}
food := append(veggies, fruits...)
字典
personSalary := make(map[string]int)
指针
b := 255
var a *int = &b
结构体
type Employee struct {
firstName, lastName string
age, salary int
}
匿名结构体
var employee struct {
firstName, lastName string
age int
}
方法
func (e Employee) displaySalary() { //e Employee 接收器 e
fmt.Printf("Salary of %s is %s%d", e.name, e.currency, e.salary)
}
func main() {
emp1 := Employee {
name: "Sam Adolf",
salary: 5000,
currency: "$",
}
emp1.displaySalary() // 调用 Employee 类型的 displaySalary() 方法
}
信道
a := make(chan int)
data := <- a // 读取信道 a
a <- data // 写入信道
类型断言与选择
- 类型断言
package main
import "fmt"
func assert(i interface{}) {
v,ok := i.(int)
fmt.Println(v,ok)
}
func main() {
var s interface{} = "hello"
assert(s)
var i interface{} = 56
assert(i)
}
- 类型选择(Type Switch)
package main
import (
"fmt"
)
func findType(i interface{}) {
switch i.(type) {
case string:
fmt.Printf("I am a string and my value is %s\n", i.(string))
case int:
fmt.Printf("I am an int and my value is %d\n", i.(int))
default:
fmt.Printf("Unknown type\n")
}
}
func main() {
findType("Naveen")
findType(77)
findType(89.98)
}
接口与空接口
- 接口
package main
import "fmt"
//创建VowelsFinder的接口 该接口有一个 FindVowels 的 方法
type VowelsFinder interface {
FindVowels() []rune
}
type MyString string
func (ms MyString) FindVowels() []rune {
var vowels []rune
for _,rune :=range ms{
if rune =='a' || rune == 'e' || rune == 'i' || rune == 'u'|| rune == 'o'{
vowels =append(vowels,rune)
}
}
return vowels
}
func main() {
name := MyString("sam Anderson")
var v VowelsFinder
v = name
fmt.Printf("Vowels are %c",v.FindVowels())
}
- 空接口
package main
import (
"fmt"
)
func describe(i interface{}) {
fmt.Printf("Type = %T, value = %v\n", i, i)
}
func main() {
s := "Hello World"
describe(s)
i := 55
describe(i)
strt := struct {
name string
}{
name: "Naveen R",
}
describe(strt)
}
}
接口用途
package main
import "fmt"
type SalaryCal interface {
Cal() int
}
// 长期员工 薪资是 basicpay 与 pf 相加之和
type Parmanent struct {
empId int
basicpay int
pf int
}
//合同员工 只有基本工资 basicpay
type Contract struct {
empId int
basicpay int
}
func (p Parmanent) Cal() int {
return p.basicpay + p.pf
}
func (c Contract) Cal() int {
return c.basicpay
}
//接收一个 SalaryCalculator 接口的切片([]SalaryCalculator)作为参数
func totalExpense(s []SalaryCal){
expense := 0
for _,v := range s{
expense += v.Cal()
}
fmt.Printf("Total Expense Per Month $%d",expense)
}
func main() {
pemp1 := Parmanent{1,5000,20}
pemp2 := Parmanent{2,6000,30}
cemp1 := Contract{3,3000}
employees := []SalaryCal{pemp1,pemp2,cemp1}
totalExpense(employees)
}
指针
指针
尽管 Go 语言没有提供继承机制,但可以通过嵌套其他的接口,创建一个新接口。
和 & 可以互相抵消,同时注意,&可以抵消掉,但&是不可以抵消的 a和&a是一样的,都是a的值,值为1 (因为&互相抵消掉了) 同理,a和&&&&a是一样的,都是1 (因为4个&互相抵消掉了)
网友评论