go语言一天入门(下)

举报
兔老大 发表于 2021/04/22 01:26:53 2021/04/22
2.3k+ 0 0
【摘要】 结构体 和c一样 package main import "fmt" type Books struct { title string author string subject string book_id int} func main() { // 创建一个新的结构体 fmt.Println(Books{"Go 语言", "www.runoob.c...

结构体

和c一样


      package main
      import "fmt"
      type Books struct {
         title string
         author string
         subject string
         book_id int
      }
      func main() {
      // 创建一个新的结构体
       fmt.Println(Books{"Go 语言", "www.runoob.com", "Go 语言教程", 6495407})
      // 也可以使用 key => value 格式
       fmt.Println(Books{title: "Go 语言", author: "www.runoob.com", subject: "Go 语言教程", book_id: 6495407})
      // 忽略的字段为 0 或 空
         fmt.Println(Books{title: "Go 语言", author: "www.runoob.com"})
      }
  
 

      {Go 语言 www.runoob.com Go 语言教程 6495407}
      {Go 语言 www.runoob.com Go 语言教程 6495407}
      {Go 语言 www.runoob.com  0}
  
 

结构体指针,函数传参


      package main
      import "fmt"
      type Books struct {
         title string
         author string
         subject string
         book_id int
      }
      func main() {
        var Book1 Books /* Declare Book1 of type Book */
        var Book2 Books /* Declare Book2 of type Book */
        /* book 1 描述 */
         Book1.title = "Go 语言"
         Book1.author = "www.runoob.com"
         Book1.subject = "Go 语言教程"
         Book1.book_id = 6495407
        /* book 2 描述 */
         Book2.title = "Python 教程"
         Book2.author = "www.runoob.com"
         Book2.subject = "Python 语言教程"
         Book2.book_id = 6495700
        /* 打印 Book1 信息 */
         printBook(&Book1)
        /* 打印 Book2 信息 */
         printBook(&Book2)
      }
      func printBook( book *Books ) {
         fmt.Printf( "Book title : %s\n", book.title)
         fmt.Printf( "Book author : %s\n", book.author)
         fmt.Printf( "Book subject : %s\n", book.subject)
         fmt.Printf( "Book book_id : %d\n", book.book_id)
      }
  
 

      Book title : Go 语言
      Book author : www.runoob.com
      Book subject : Go 语言教程
      Book book_id : 6495407
      Book title : Python 教程
      Book author : www.runoob.com
      Book subject : Python 语言教程
      Book book_id : 6495700
  
 

切片

和py一样。


      package main
      import "fmt"
      func main() {
        var numbers []int
         printSlice(numbers)
        /* 允许追加空切片 */
         numbers = append(numbers, 0)
         printSlice(numbers)
        /* 向切片添加一个元素 */
         numbers = append(numbers, 1)
         printSlice(numbers)
        /* 同时添加多个元素 */
         numbers = append(numbers, 2,3,4)
         printSlice(numbers)
        /* 创建切片 numbers1 是之前切片的两倍容量*/
         numbers1 := make([]int, len(numbers), (cap(numbers))*2)
        /* 拷贝 numbers 的内容到 numbers1 */
        copy(numbers1,numbers)
         printSlice(numbers1)
      }
      func printSlice(x []int){
         fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
      }
      /*
      len=0 cap=0 slice=[]
      len=1 cap=1 slice=[0]
      len=2 cap=2 slice=[0 1]
      len=5 cap=6 slice=[0 1 2 3 4]
      len=5 cap=12 slice=[0 1 2 3 4]
      */
  
 

range

range 关键字用于 for 循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素。在数组和切片中它返回元素的索引和索引对应的值,在集合中返回 key-value 对。


      package main
      import "fmt"
      func main() {
      //这是我们使用range去求一个slice的和。使用数组跟这个很类似
       nums := []int{2, 3, 4}
       sum := 0
      for _, num := range nums {
       sum += num
       }
       fmt.Println("sum:", sum)
      //在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。
      for i, num := range nums {
      if num == 3 {
       fmt.Println("index:", i)
       }
       }
      //range也可以用在map的键值对上。
       kvs := map[string]string{"a": "apple", "b": "banana"}
      for k, v := range kvs {
       fmt.Printf("%s -> %s\n", k, v)
       }
      //range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。
      for i, c := range "go" {
       fmt.Println(i, c)
       }
      }
  
 

      sum: 9
      index: 1
      a -> apple
      b -> banana
      0 103
      1 111
  
 

map

可以使用内建函数 make 也可以使用 map 关键字来定义 Map:

/* 声明变量,默认 map 是 nil */
var map_variable map[key_data_type]value_data_type

/* 使用 make 函数 */
map_variable := make(map[key_data_type]value_data_type)

如果不初始化 map,那么就会创建一个 nil map。nil map 不能用来存放键值对


      package main
      import "fmt"
      func main() {
      var countryCapitalMap map[string]string /*创建集合 */
       countryCapitalMap = make(map[string]string)
      /* map插入key - value对,各个国家对应的首都 */
       countryCapitalMap [ "France" ] = "巴黎"
       countryCapitalMap [ "Italy" ] = "罗马"
       countryCapitalMap [ "Japan" ] = "东京"
       countryCapitalMap [ "India " ] = "新德里"
      /*使用键输出地图值 */
      for country := range countryCapitalMap {
       fmt.Println(country, "首都是", countryCapitalMap [country])
       }
      /*查看元素在集合中是否存在 */
       capital, ok := countryCapitalMap [ "American" ] /*如果确定是真实的,则存在,否则不存在 */
      /*fmt.Println(capital) */
      /*fmt.Println(ok) */
      if (ok) {
       fmt.Println("American 的首都是", capital)
       } else {
       fmt.Println("American 的首都不存在")
       }
      }
  
 

      France 首都是 巴黎
      Italy 首都是 罗马
      Japan 首都是 东京
      India  首都是 新德里
      American 的首都不存在
  
 

注:删除:delete(countryCapitalMap, "France")

语言类型转换

类型转换用于将一种数据类型的变量转换为另外一种类型的变量。Go 语言类型转换基本格式如下:

type_name(expression)

type_name 为类型,expression 为表达式。

如float32(5)等。

接口实例


      package main
      import (
      "fmt"
      )
      type Phone interface {
       call()
      }
      type NokiaPhone struct {
      }
      func (nokiaPhone NokiaPhone) call() {
       fmt.Println("I am Nokia, I can call you!")
      }
      type IPhone struct {
      }
      func (iPhone IPhone) call() {
       fmt.Println("I am iPhone, I can call you!")
      }
      func main() {
      var phone Phone
       phone = new(NokiaPhone)
       phone.call()
       phone = new(IPhone)
       phone.call()
      }
  
 

在上面的例子中,我们定义了一个接口Phone,接口里面有一个方法call()。然后我们在main函数里面定义了一个Phone类型变量,并分别为之赋值为NokiaPhone和IPhone。然后调用call()方法,输出结果如下:

I am Nokia, I can call you!
I am iPhone, I can call you!

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/106196796

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。