Six months after learning Ruby, I wanted to learn another language, so I touched Go a little.
When solving the FizzBuzz problem with Ruby, there are various ways to write it, such as for, while, but this time I wrote it with the times method.
fizzbuzz.rb
1..100.times do |i|
if i%15==0
puts "FizzBuzz"
elsif i%3==0
puts "Fizz"
elsif i%5==0
puts "Buzz"
else
puts i
end
end
When written in Go, it became as follows.
fizzbuzz.go
package main
import (
"fmt"
)
func main() {
for i := 0; i < 100; i++ {
if i%5 == 0 && i%3 == 0 {
fmt.Println("Fizz Buzz")
} else if i%3 == 0 {
fmt.Println("Fizz")
} else if i%5 == 0 {
fmt.Println("Buzz")
} else {
fmt.Println(i)
}
}
}
There were some differences compared to Ruby even if I made a simple program, so I tried to summarize it myself.
--About package --About import --About iterative processing -About: =
package
In Go, programming elements belong to some kind of package, and you must declare the package.
When I created an empty file and ran go run test.go
, I got an error such as ʻexpected'package', found'EOF'`.
Therefore, if there is no package or main function as shown in the code below, an error will occur at runtime.
test.go
package main
func main() {
}
import
In Go, if you use a function that is not written in the main package, you must describe the package name that has that function.
This is an image like the standard library
in the Ruby library.
For Ruby
standard_library.rb
require 'Time'
p Time.strptime('2020-03-21T01:58:30+09:00', '%Y-%m-%dT%H:%M:%S%z')
# -> 2020-03-21 01:58:30 +0900
For Go
hello.go
package main
import("fmt")
func main() {
fmt.Println("Hello World")
// -> Hello World
}
In Ruby, there are various ways to write for, while, times, etc. when performing iterative processing. In Go, only for statement is used for iterative processing.
However, it is also possible to write like foreach as shown below.
foreach.go
package main
import (
"fmt"
)
func main() {
fruits := map[string]string{
"apple": "Apple",
"banana": "banana",
"pineapple": "pineapple",
}
for key, value := range fruits {
fmt.Println("key:", key, " value:", value)
}
}
// key: apple value:Apple
// key: banana value:banana
// key: pineapple value:pineapple
When explicitly defining a variable with go, describe as follows.
variable.go
package main
import ("fmt")
func main() {
var x,y,z int
x = 1
y = 2
z = 3
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)
}
// 1
// 2
// 3
However, it is also possible to implicitly define a variable, in which case it will be as follows.
variable.go
package main
import ("fmt")
func main() {
x := 1
y := 2
z := 3
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)
}
// 1
// 2
// 3
Since you can omit the type specification, you can improve the development efficiency by writing here.
Learn the basic grammar of Go Learn golang from the basics: Control structure
Recommended Posts