Go语言入门(五)结构体&练习

wx5b285b48ed74e · · 498 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

结构体&练习

结构体

定义

Go中的面向对象是通过 struct来实现的,struct是用户自定义的类型

//定义结构体
/定义结构体
type User struct {
   Name       string
   Gender     string
   Age        int
   AvatarUrl  string
}

func useStruct() {
   //初始化结构体1
   var user1 User
   user1.Name = "jeson"
   user1.Gender = "male"
   user1.Age  = 20
   user1.AvatarUrl = "http://baidu.com"
   //初始化结构体2
   user2 := User{
      Name:      "miky",
      Gender:    "female",
      Age:       18,
   }
   fmt.Println(user1,user2)
   //空结构体
   user3 := User{}
   fmt.Println(user3)
}

结构体的特性

  • struct的内存布局:占用一段连续的内存空间
  • 结构体没有构造函数,需要自己实现
//定义结构体
type User struct {
   Name       string
   Gender     string
   Age        int
   AvatarUrl  string
}

// 定义构造函数
func NewUser(name,gender string,age int,url string) User {
   var user User
   user.Name = name
   user.Gender = gender
   user.Age = age
   user.AvatarUrl = url
   return user
}
//使用构造函数
func main() {
   user1 := NewUser("zhansan","male",23,"xxx")
   fmt.Println(user1)
}

匿名字段和嵌套的使用

type People struct {
   Name        string
   Gender      string
   Age         int
   AvatarUrl   string
   //匿名字段
   int
   string
   //结构体嵌套
   address      Address
}
type Address struct {
   City       string
   Province   string
}

func nimingStructs() {
   var people People
   people.Name = "abc"
   people.Gender = "male"
   people.AvatarUrl = "www.qq.com"
   //直接用结构体名引用匿名字段
   people.int = 99
   people.string = "hello world"
   //嵌套结构体的使用
   people.address.City = "beijing"
   people.address.Province = "beijing"
   fmt.Printf("%#v\n",people)
   //
   people1 := People{
      Name:      "alley",
      Gender:    "male",
      Age:       12,
      AvatarUrl: "www.baidu.com",
      int:       0,
      string:    "dd",
      address:   Address{
         City: "Lanzhou",
         Province: "Gansu",
      },
   }
   fmt.Printf("%#v\n",people1)
}
  • 匿名结构体: 继承
  • 字段可见性: 大写表示公开可以访问,小写表示私有

tag与结构体的应用

tag是结构体原信息,可以在运行的时候通过反射的机制读取出来

type User struct {
   Name     string    `json:"name"`
   Gender   string   `json:"gender"`
   Age      int     `json:"age"`
   AvatarUrl string   `json:"avataurl"`
}

func jsonMarshal () {
   var user User
   user.Name = "jeck"
   user.Gender = "male"
   user.Age = 20
   user.AvatarUrl = "xxx"

   //json 格式
   data,err := json.Marshal(user)
   if err != nil {
      fmt.Printf("marshal failed %v\n",err)
      return
   }
   fmt.Printf("json:%v\n",string(data))
}

练习

  • 实现1-100内的质数的打印
func isPrime(n int) bool {
   var flag = true
   for j:=2;j<n;j++ {
      if (n%j==0) {
         flag = false
         break
      }
   }
   return flag
}

func zhishu() {
   var n int
   fmt.Printf("Please input n:\n")
   fmt.Scanf("%d",&n)
   for i := 2;i<n;i++ {
      if isPrime(i) {
         fmt.Printf("%d is prime\n",i)
      }
   }
}
  • 输入一行字符,分别计算簇字母空格数字和其他字符的个数

v1初始版

func main() {
   str := "how are you! i am fine! thank you.welcome"
   var tmp []rune
   var wordCount map[string]int = make(map[string]int,10)
   var chars []rune = []rune(str)
   for i:=0; i<len(str);i++ {
      if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
         tmp = append(tmp,chars[i])
      }else {
         word := string(tmp)
         if len(word) > 0 {
            count,ok := wordCount[word]
            if !ok {
               wordCount[word] = 1
            } else {
               wordCount[word] = count+1
            }
         }
         tmp = tmp[0:0]
      }
   }
   if len(tmp) > 0{
      word := string(tmp)
      if len(word) > 0 {
         count,ok := wordCount[word]
         if !ok {
            wordCount[word] = 1
         } else {
            wordCount[word] = count+1
         }
      }

   }
   for key,val := range wordCount {
      fmt.Printf("word:%s,出现的次数%d\n",key,val)
   }
}

v2函数抽象版本

func addWorld(wordCount map[string]int,chars []rune) {
   word := string(chars)
   if len(word) > 0 {
      count,ok := wordCount[word]
      if !ok {
         wordCount[word] = 1
      } else {
         wordCount[word] = count+1
      }
   }
}

func main() {
   str := "how are you! i am fine! thank you.welcome"
   var tmp []rune
   var wordCount map[string]int = make(map[string]int,10)
   var chars []rune = []rune(str)
   for i:=0; i<len(str);i++ {
      if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z') {
         tmp = append(tmp,chars[i])
      }else {
         addWorld(wordCount,tmp)
         tmp = tmp[0:0]
      }
   }
   if len(tmp) > 0{
      addWorld(wordCount,tmp)
   }
   for key,val := range wordCount {
      fmt.Printf("word:%s,出现的次数%d\n",key,val)
   }
}
  • 字符统计(包含中文)
func addWord(charCount map[rune]int,char rune){
   count,ok := charCount[char]
   if !ok {
      charCount[char] = 1
   }else {
      charCount[char] = count +1
   }
}

func main() {
   str := "sds sds,Let us go go go,学习好的 any sds!@lili"
   var charCount map[rune]int = make(map[rune]int,10)
   var chars []rune = []rune(str)

   for i:=0;i<len(chars);i++ {
      addWord(charCount,chars[i])
   }

   for key,val := range charCount {
      fmt.Printf("keys:%c val: %d\n",key,val)
   }
}
  • 实现一个学生管理系统,每个学生有分数,年级,性别,名字等信息,用户可以在控制台添加学生,修改学生信息,打印学生列表的功能
type Student struct {
   Id         string     `json:"id"`
   Name       string     `json:"name"`
   Age        int         `json:"name"`
   Gender     string      `json:"gender"`
   Score      float32     `json:"score"`
}

func showMenu()  {
   fmt.Printf("please select:\n")
   fmt.Printf("1. 添加学生信息\n")
   fmt.Printf("2. 修改学生信息\n")
   fmt.Printf("3. 显示学生信息\n")
   fmt.Printf("4. 退出\n")
}

func getStudentInfo() Student {
   var stu Student
   fmt.Printf("please input id:\n")
   fmt.Scanf("%s\n",&stu.Id)
   fmt.Printf("please input name:\n")
   fmt.Scanf("%s\n",&stu.Name)
   fmt.Printf("please input age:\n")
   fmt.Scanf("%d\n",&stu.Age)
   fmt.Printf("please input gender:\n")
   fmt.Scanf("%s\n",&stu.Gender)
   fmt.Printf("please input score:\n")
   fmt.Scanf("%f\n",&stu.Score)
   return stu
}

func addStudent(allStudent map[string]Student)  {
   stu := getStudentInfo()
   _,ok := allStudent[stu.Id]
   if ok {
      fmt.Printf("student %s is exists\n",stu.Id)
      return
   }
   allStudent[stu.Id] = stu
}

func showStudentList(allStudent map[string]Student) {
   for _,val := range allStudent {
      fmt.Printf("#########分隔线##########\n")
      fmt.Printf("id:%s\n",val.Id)
      fmt.Printf("name:%s\n",val.Name)
      fmt.Printf("age:%d\n",val.Age)
      fmt.Printf("gender:%s\n",val.Gender)
      fmt.Printf("score:%f\n",val.Score)
      fmt.Printf("#########分隔线##########\n")

   }
}

func modifyStudent(allStudent map[string]Student)  {
   stu := getStudentInfo()
   _,ok := allStudent[stu.Id]
   if !ok {
      fmt.Printf("student %s is not exists\n",stu.Id)
      return
   }
   allStudent[stu.Id] = stu
}

func main() {
   var allStudent map[string]Student = make(map[string]Student,100)
   for {
      showMenu()
      var sel int
      fmt.Scanf("%d\n",&sel)
      switch sel {
      case 1:
         addStudent(allStudent)
      case 2:
         modifyStudent(allStudent)
      case 3:
         showStudentList(allStudent)
      case 4:
         os.Exit(0)
      }
   }
}

有疑问加站长微信联系(非本文作者)

本文来自:51CTO博客

感谢作者:wx5b285b48ed74e

查看原文:Go语言入门(五)结构体&练习

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

498 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传