手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表2013年05月23日的文章

对着谢大的教程写代码(一)

 谢大的教程在:https://github.com/astaxie/build-web-application-with-golang

在复刻和学习的过程中,把问题记录下来的笔记
 
1、
XML/HTML代码
  1. // 声明一个数组  
  2. var array = [10]byte{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}  
  3. // 声明两个slice  
  4. var aSlice, bSlice []byte  
  5.   
  6. // 演示一些简便操作  
  7. aSlice = array[:3] // 等价于aSlice = array[0:3] aSlice包含元素: a,b,c  
  8. aSlice = array[5:] // 等价于aSlice = array[5:10] aSlice包含元素: f,g,h,i,j  
  9. aSlice = array[:]  // 等价于aSlice = array[0:10] 这样aSlice包含了全部的元素  
  10.   
  11. // 从slice中获取slice  
  12. aSlice = array[3:7]  // aSlice包含元素: d,e,f,g,len=4cap=7  
  13. bSlice = aSlice[1:3] // bSlice 包含aSlice[1], aSlice[2] 也就是含有: e,f  
  14. bSlice = aSlice[:3]  // bSlice 包含 aSlice[0], aSlice[1], aSlice[2] 也就是含有: d,e,f  
  15. bSlice = aSlice[0:5] // 对slice的slice可以在cap范围内扩展,此时bSlice包含:d,e,f,g,h  
  16. bSlice = aSlice[:]   // bSlice包含所有aSlice的元素: d,e,f,g  
主要是加深颜色的那句。。。。
2、
go代码
  1. type human struct {  
  2.     name   string  
  3.     age    string  
  4.     height int  
  5. }  
  6. type student struct {  
  7.     human  
  8.     skills  
  9.     int  
  10.     age        int  
  11.     speciality string  
  12. }  
  13. func (h *human) sayhi() {  
  14.     fmt.Printf("human say hello, i'm %s \n", h.name)  
  15. }  
  16. func (h *human) gogo() {  
  17.     fmt.Println("gogogo");  
  18. }     
  19. type men interface{  
  20.     sayhi()  
  21.     gogo()  
  22. }  
  23.   
  24. 然后用的地方:  
  25.     mike := student{human:human{name:"mike"}}  
  26.     var i men;  
  27.     i = mike;  
  28.     i.sayhi();  
因为这是早期的所见所得编辑器。对于代码高亮做的不好。忍忍吧。。。
上面的代码是会出错的。
cannot use mike (type student) as type men in assignment:
student does not implement men (gogo method requires pointer receiver)
需要:mike := &student{human:human{name:"mike"}}
看到没,在student前有个取址符。主要是因为方法指定的是:(h *human),如果是(h human),就不需要取址符了
*human 是指针,但是你mike不是指针,只是对象,所以没有实现这两个方法,才会报错
然后谢大给出了这个:http://segmentfault.com/q/1010000000198984#a-1020000000199002,说是里面有解释
XML/HTML代码
  1. 假设T是struct,那么Go里面遵循下面几个原则:  
  2.   
  3.    T的方法集仅拥有 T Receiver 方法。  
  4.    *T 方法集则包含全部方法 (T + *T)。  

  5. 所以你上面的例子dept1应该是拥有方法:Name和SetName    
  6. 而&dept1拥有方法:Name、SetName和Relocate  
  7. 这个就是Go里面在设计方法的时候需要注意Receiver的类型  

Tags: go, astaxie