专栏名称: 狗厂
目录
相关文章推荐
51好读  ›  专栏  ›  狗厂

Java to Go 学习指南

狗厂  · 掘金  ·  · 2018-04-16 06:25

正文

这篇指南为了能够帮助Java程序员快速深入了解Go语言特性!

主要区别

面向对象:

  • Go 语言的面向对象编程(OOP)非常简洁而优雅。说它简洁,简洁之处在于,它没有了OOP中很多概念,比如:继承、虚函数、构造函数和析构函数、隐藏的this指针等等。说它优雅,是它的面向对象(OOP)是语言类型系统(type system)中的天然的一部分。整个类型系统通过接口(interface)串联,浑然一体。

employee.go

  1. package employee
  2. import (
  3. "fmt"
  4. )
  5. type employee struct {
  6. firstName string
  7. lastName string
  8. totalLeaves int
  9. leavesTaken int
  10. }
  11. func New(firstName string, lastName string, totalLeave int, leavesTaken int) employee {
  12. e := employee {firstName, lastName, totalLeave, leavesTaken}
  13. return e
  14. }
  15. func (e *employee) LeavesRemaining() {
  16. fmt.Printf("%s %s has %d leaves remaining", e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))
  17. }

main.go

  1. package main
  2. import "oop/employee"
  3. func main() {
  4. e := employee.New("Sam", "Adolf", 30, 20)
  5. e.LeavesRemaining()
  6. }

Go interface

  1. package main
  2. import "fmt"
  3. import "math"
  4. // Here's a basic interface for geometric shapes.
  5. type geometry interface {
  6. area() float64
  7. perim() float64
  8. }
  9. // For our example we'll implement this interface on
  10. // `rect` and `circle` types.
  11. type rect struct {
  12. width, height float64
  13. }
  14. type circle struct {
  15. radius float64
  16. }
  17. // To implement an interface in Go, we just need to
  18. // implement all the methods in the interface. Here we
  19. // implement `geometry` on `rect`s.
  20. func (r rect) area() float64 {
  21. return r.width * r.height
  22. }
  23. func (r rect) perim() float64 {
  24. return 2*r.width + 2*r.height
  25. }
  26. // The implementation for `circle`s.
  27. func (c circle) area() float64 {
  28. return math.Pi * c.radius * c.radius
  29. }
  30. func (c circle) perim() float64 {
  31. return 2 * math.Pi * c.radius
  32. }
  33. // If a variable has an interface type, then we can call
  34. // methods that are in the named interface. Here's a
  35. // generic `measure` function taking advantage of this
  36. // to work on any `geometry`.
  37. func measure(g geometry) {
  38. fmt.Println(g)
  39. fmt.Println(g.area())
  40. fmt.Println(g.perim())
  41. }
  42. func main() {
  43. r := rect{width: 3, height: 4}
  44. c := circle{radius: 5}
  45. // The `circle` and `rect` struct types both
  46. // implement the `geometry` interface so we can use
  47. // instances of
  48. // these structs as arguments to `measure`.
  49. measure(r)
  50. measure(c)
  51. }

方法:







请到「今天看啥」查看全文