zoukankan      html  css  js  c++  java
  • Go 方法和接收者

     1 package main
     2 
     3 import (
     4     "fmt"
     5 )
     6 
     7 //面向对象
     8 //go仅支持封装,不支持继承和多态
     9 //go语言中没有class,只要struct
    10 //不论地址还是结构本身,一律使用.来访问成员
    11 //要改变内容必须使用指针接收者
    12 //结构过大考虑指针接收者
    13 //值接收者是go语言特有
    14 //封装 15 //名字一般使用CamelCase 16 //首字母大写: public 17 //首字母小写:private 18 19 //20 //每个目录一个包,包名可以与目录不一样 21 //main包包含可执行入口,只有一个main包 22 //为结构定义的方法必须放在同一个包内,但是可以是不同文件 23 24 25 type treeNode struct { 26 value int 27 left, right *treeNode 28 } 29 30 func (node treeNode) print() { //显示定义和命名方法接收者(括号里) 31 32 fmt.Print(node.value) //只有使用指针才可以改变结构内容 33 fmt.Println() 34 } 35 36 func (node *treeNode) setValue ( value int) { //使用指针作为方法接收者 37 if node == nil { 38 fmt.Println("setting value to nil node") //nil指针也可以调用方法 39 return 40 } 41 node.value = value 42 } 43 44 func (node *treeNode ) traverse(){ 45 if node == nil{ 46 return 47 } 48 node.left.traverse() 49 node.print() 50 node.right.traverse() 51 } 52 53 func main() { 54 var root treeNode 55 fmt.Println(root) //{0 <nil> <nil>} 56 57 root = treeNode{value:3} 58 root.left = &treeNode{} 59 root.right = &treeNode{5,nil,nil} 60 root.right.left = new(treeNode) 61 62 nodes := []treeNode { 63 {value: 3}, 64 {}, 65 {6,nil,&root}, 66 } 67 fmt.Println(nodes) //[{3 <nil> <nil>} {0 <nil> <nil>} {6 <nil> 0xc04205a3e0}] 68 69 root.print() // 3 70 fmt.Println() 71 root.right.left.setValue(100) 72 root.right.left.print() //100 73 fmt.Println() 74 75 var pRoot *treeNode 76 pRoot.setValue(200) //setting value to nil node 77 pRoot = &root 78 pRoot.setValue(300) 79 pRoot.print() //300 80 81 root.traverse() //300 0 300 100 5 82 }
  • 相关阅读:
    EF中嵌套类的where查询
    VS中添加Web References
    DropDownList绑定数据源后,要插入项的处理
    CheckBoxList选中某项,获取其它项是否是选中
    WebAPI的使用
    HTML5中像网页中保存cookie的实现
    日志切割之Logrotate
    CentOS防火墙iptables使用
    CentOS7安装Python3
    Keepalived高可用
  • 原文地址:https://www.cnblogs.com/yuxiaoba/p/9346882.html
Copyright © 2011-2022 走看看