learn-golang-with-tdd
[TOC]
Hello, World
What I learned
if
works like other programming languages, without(
parenthesis)
- blocks are defined with
{
curly braces}
- variables are
assigneddeclared like this:varName := value
- I researched and realized that
:=
for short variable declarations=
for variable declarations and assignments.
- I researched and realized that
t.Errorf
prints a message when a test fails.%q
means "string surrounded with double quotes", in the string format contextfunc greetingPrefix(language string) (prefix string)
creates a named return value
- this creates a variable calledprefix
in the function
- it will be assigned the "zero" value. In this case (string
):""
- in Go, public functions start with a capital letter and private ones start with a lowercase.
Few rules to writing tests
- file name must be
${something}_test.go
- the test function must start with
Test
- test function takes only one argument
t *testing.T
- in order to use
*testing.T
type you need toimport "testing"
Didn't work
# installing local documentation
go install golang.org/x/tools/cmd/godoc@latest
# after installing this command still don't work
godoc -http :8000
# ERROR: 'godoc' command not found
Starting a module
create the hello
module:
mkdir hello
cd hello
go mod init hello
# check if the "go.mod" file was created
hello.go
:
package main
import "fmt"
// Hello() is a separated function
// to make it testable
func Hello() string {
return "Hello, world"
}
func main() {
fmt.Println(Hello())
}
hello_test.go
:
package main
import "testing"
func TestHello(t *testing.T) {
got := Hello()
want := "Hello, world"
if got != want {
t.Errorf("got %q want %q", got, want)
}
}
Run the test:
go test