37
loading...
This website collects cookies to deliver better user experience
// helloworld.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
$ go run helloworld.go
Hello, World!
$ go build helloworld.go
$ ./helloworld
Hello, World!
fmt
, pronounced fumptimport (
"fmt"
"math"
)
golint
will help you out with this automatically, but let us save that for later.main
function is special it acts as the entry point to our executable.main
is special and does not take any parameters and does as default not return anything, which makes it really hard to test (do read this post on the topic), that aside, lets have a look at go functions in general.main
), would have the following signature:func f() {...}
func f(number int) {}
fun f(operand1, operand2 int) int {}
fun f(operand1, operand2 int) (int, int) {}
main
is hard.package main
import (
"fmt"
)
func main() {
fmt.Printf("%s", HelloWorld())
}
// HelloWorld returns universal programming language greeting in english
func HelloWorld() string {
return "Hello, World!"
}
main_test.go
package main
import "testing"
func TestHelloWorld(t *testing.T) {
expected := "Hello, World!"
if observed := HelloWorld(); observed != expected {
t.Fatalf("HelloWorld() = %v, want %v", observed, expected)
}
}
helloworld.go
(above)testing
TestHelloWord
and it takes the following arguments:t
. which is a pointer of the type: testing.T
Hello, World!
.HelloWorld
function and tests if we our return value is not matching our expected result from the previous line.t.Fatalf
and output some diagnostics, to help us address potential issues in our implementation.go test
we are however met with and error cannot import "main
go mod init helloworld
go.mod
, with the following contents:module helloworld
go 1.16
go test
go.mod
file, is for our Go toolchain.Learn Go with Tests, which outlines how to structure you Go projects, so you get a sane foundation supporting automated testing, even if you are not into test-driven development (TDD).
Check out a proposal for a Go Developer Roadmap for learning Go in 2020
Or you could learn fundamental Algorithms with Go
IF you like me is a complete n00b consider following the Go track on Exercism.io or the Go katas on Codewars.com