go语言基础篇1

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NiQinGe/article/details/81541580
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello World")

	fmt.Println(getStr())

	getLength()
	fmt.Println()

	values := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	resultChan := make(chan int, 2)
	go sum(values[:len(values)/2], resultChan)
	go sum(values[len(values)/2:], resultChan)
	sum1, sum2 := <-resultChan, <-resultChan // 接收结果
	fmt.Println("Result:", sum1, sum2, sum1+sum2)

	new(HuaWeiPhone).cell()
	new(XiaoMiPhone).cell()
	fmt.Println(new(XiaoMiPhone).email())
	fmt.Println(new(XiaoMiPhone).online(44))

	fmt.Println(testIfElse(2, 1))
}

func testIfElse(num1, num2 int) bool {
	if num2 > num1 {
		return true
	} else {
		return false
	}
}

func getStr() (str1 string, str2 string) { // 指定了返回字符串的变量名称
	str1 = "zhangsan"
	str2 = "lisi"
	return
}

func getLength() {
	str := "Hello,世界"
	n := len(str)
	for i := 0; i < n; i++ {
		ch := str[i] // 依据下标取字符串中的字符,类型为byte
		fmt.Println(i, ch)
	}
}

func sum(values []int, resultChan chan int) {
	sum := 0
	for _, value := range values {
		sum += value
		fmt.Print(sum, ",")
	}
	resultChan <- sum // 将计算结果发送到channel中
}

/********接口,start**********/
type HuaWeiPhone struct {
}

type XiaoMiPhone struct {
}

type Phone interface {
	cell()                     // 无返回
	email() bool               // 返回一个布尔值
	online(num int) (int, int) // 传入一个参数并返回两个参数
}

func (xiaomi XiaoMiPhone) cell() {
	fmt.Println("xiaomi")
}

func (xiaomi XiaoMiPhone) online(num int) (int, int) {
	return num, 2
}

func (xiaomi XiaoMiPhone) email() bool {
	var result bool
	if 2 > 3 {
		result = true
	} else {
		result = false
	}
	return result
}

func (huawei HuaWeiPhone) cell() {
	fmt.Println("huawei")
}

/**********接口,end******/

 

猜你喜欢

转载自blog.csdn.net/NiQinGe/article/details/81541580