![](https://www.dazhuanlan.com/webchat.jpg)
Go 学习笔记,持续更新。 原文请参考: http://kimh.github.io/blog/en/go/how-can-i-do-x-in-ruby-with-go-part-1/
Create Array
Ruby:
1 2
|
numbers = [1,2,3] fruits = ["apple", "banana", "grape"]
|
Go:
1 2
|
numbers := []int{1,2,3} fruits := []string{"apple", "banana", "grape"}
|
Append an element to array
Ruby:
1 2
|
numbers = [1,2,3] numbers << 4
|
Go:
1 2
|
numbers := []int{1,2,3} numbers.append(numbers, 4)
|
Concatenate arryas
Ruby:
1 2 3
|
numbers1 = [1,2,3] numbers2 = [4,5,6] numbers1 = numbers1 + numbers2
|
Go:
1 2 3
|
numbers1 := []int{1,2,3} numbers2 := []int{4,5,6} numbers1 = append(numbers1, numbers2...)
|
Go:
1 2
|
numbers1 := []int{1,2,3} numbers1 = append(numbers1, 4, 5, 6)
|
Create multi dimension array
Ruby:
1
|
multi_array = [[1,2,3],[4,5,6]]
|
Go:
1
|
multi_array := [][]int{{1, 2, 3}, {4,5,6}}
|
Create empty array
Ruby:
Go:
Iterate an array
Ruby:
1 2
|
numbers = [1,2,3] numbets.each {|num| puts num }
|
Go:
1 2 3 4 5
|
numbers := []int{1,2,3} for _, num := range numbers { fmt.Println(num) }
|
Looping N times
Ruby:
1
|
5.times {|num| puts num}
|
Go:
1 2 3
|
for num := 0; num < 5; num ++ { fmt.Println(num) }
|
Clone array
Ruby:
1
|
new_array = old_array.clone
|
Go:
1 2 3
|
new_array := make([]int, len(old_array)) copy(new_array, old_array)
|
Accessing elements of array by range
Ruby:
1 2
|
numbers = [1,2,3,4] numbers[0..3]
|
Go:
1 2
|
go_array := []int{1,2,3,4} go_array[0:4]
|
Compare array
Ruby:
1 2 3
|
if array1 == array2 puts "Same array" end
|
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
go_array := []int{1, 2, 3, 4, 5, 6, 7} bb_array := []int{3, 2, 3, 4, 5, 6, 7} same := true for i, ele := range go_array { if bb_array[i] != ele { same = false break } } if same == true { fmt.Println("Same slice") }
|
Check if array include an element
Ruby:
1 2 3 4 5
|
fruits = ["apple", "banana", "grape"] if fruits.include?("apple") puts "include!" end
|
Go:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
include := false fruits := []string{"apple", "banana", "grape"} for _, ele := range fruits { if ele == "apple" { include = true break } } if include == true { fmt.Println("Included") }
|
Define a method with variable length argument
Ruby:
1 2 3
|
def (*args) args.each {|arg| puts arg} end
|
Go:
1 2 3 4 5 6 7
|
func (arguments ...int) { for _, arg := range arguments { fmt.Println(arg) } } foo(1,2,3,4,5)
|
Nil checking
Ruby:
1 2 3
|
if val.nil? puts "val is nil" end
|
Go:
1 2 3 4 5 6 7 8 9 10 11
|
var str string if str =="" { fmt.Println("str is empty") } var i int if i == 0 { fmt.Println("i is zero") }
|
近期评论