Java to Go 学习指南

1,099 阅读2分钟
原文链接: xiequan.info

这篇指南为了能够帮助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. }

方法:

  1. type MyType struct {
  2. n int
  3. }
  4. func (p *MyType) Value() int { return p.n }
  5. func main() {
  6. pm := new(MyType)
  7. fmt.Println(pm.Value()) // 0 (zero value)
  8. }

函数类型:

  1. type Operator func(x float64) float64
  2. // Map applies op to each element of a.
  3. func Map(op Operator, a []float64) []float64 {
  4. res := make([]float64, len(a))
  5. for i, x := range a {
  6. res[i] = op(x)
  7. }
  8. return res
  9. }
  10. func main() {
  11. op := math.Abs
  12. a := []float64{1, -2}
  13. b := Map(op, a)
  14. fmt.Println(b) // [1 2]
  15. c := Map(func(x float64) float64 { return 10 * x }, b)
  16. fmt.Println(c) // [10, 20]
  17. }

匿名函数与闭包:

  1. func Slice(slice interface{}, less func(i, j int) bool)
  2. people := []string{"Alice", "Bob", "Dave"}
  3. sort.Slice(people, func(i, j int) bool {
  4. return len(people[i]) < len(people[j])
  5. })
  6. fmt.Println(people)
  7. // Output: [Bob Dave Alice]
  8. // OR
  9. people := []string{"Alice", "Bob", "Dave"}
  10. less := func(i, j int) bool {
  11. return len(people[i]) < len(people[j])
  12. }
  13. sort.Slice(people, less)
  14. // Count prints the number of times it has been invoked.
  15. func New() (Count func()) {
  16. n := 0
  17. return func() {
  18. n++
  19. fmt.Println(n)
  20. }
  21. }
  22. func main() {
  23. f1, f2 := New(), New()
  24. f1() // 1
  25. f2() // 1 (different n)
  26. f1() // 2
  27. f2() // 2
  28. }

指针:

  1. type Student struct {
  2. Name string
  3. }
  4. var ps *Student = new(Student) // ps holds the address of the new struct
  5. ps := new(Student)
  6. s := Student{"Alice"} // s holds the actual struct
  7. ps := &s // ps holds the address of the struct
  8. // Bob is a function that has no effect.
  9. func Bob(s Student) {
  10. s.Name = "Bob" // changes only the local copy
  11. }
  12. // Charlie sets pp.Name to "Charlie".
  13. func Charlie(ps *Student) {
  14. ps.Name = "Charlie"
  15. }
  16. func main() {
  17. s := Student{"Alice"}
  18. Bob(s)
  19. fmt.Println(s) // prints {Alice}
  20. Charlie(&s)
  21. fmt.Println(s) // prints {Charlie}
  22. }

错误处理:

  1. type error interface {
  2. Error() string
  3. }
  4. f, err := os.Open("filename.ext")
  5. if err != nil {
  6. log.Fatal(err)
  7. }
  8. // coustome error
  9. err := errors.New("Houston, we have a problem")

 
并发

未完待续。。。。