DEV Community

Rahul Upakare
Rahul Upakare

Posted on

2 1

Learn Go with "Hello, world" programs

Hello, world

A "hello, world" program is a program which outputs or displays "hello, world" message. It often illustrates the basic syntax of programming language. Perhaps, this tradition was started from the book The C Programming Language, by Brian W. Kernighan and Dennis M. Ritchie, 1978.

Recently, mostly for fun learning, I've started writing "hello, world" program to try out Go language. I think it becomes easy to understand the code syntax and concepts, if you already know what output the code is going to have. 

In this post, I am showing you the initial list of "hello, world" programs, which I plan to keep updating with explanation and adding more over a period of time. I would be glad to hear your feedback and open to your contributions to make it a useful resource. Github Repository

Print (traditional)

package main
import "fmt"
func main() {
fmt.Println("Hello, 世界")
}

Variables - string

package main
import "fmt"
func main() {
var s string
s = "Hello, 世界"
fmt.Println(s)
}
view raw hello_string.go hosted with ❤ by GitHub

Variables - int

package main
import "fmt"
func main() {
var h = 72
e := 101
var w int32 = 19990
var d int64 = 30028
fmt.Printf("%c%cllo, %c%c\n", h, e, w, d)
}
view raw hello_int.go hosted with ❤ by GitHub

Variables - boolean

package main
import "fmt"
func main() {
var flag bool
flag = true
if flag != false {
fmt.Println("Hello, 世界")
}
}
view raw hello_bool.go hosted with ❤ by GitHub

Short assignment

package main
import "fmt"
func main() {
s := "Hello, 世界"
fmt.Println(s)
}
view raw hello_value.go hosted with ❤ by GitHub

Constant

package main
import "fmt"
func main() {
const s = "Hello, 世界"
fmt.Println(s)
}

if condition

package main
import "fmt"
func main() {
s := "Hello, 世界"
if len(s) > 0 {
fmt.Println(s)
}
}
view raw hello_if.go hosted with ❤ by GitHub

for loop

package main
import "fmt"
func main() {
for i := 0; i < 1; i++ {
fmt.Println("Hello, 世界")
}
}
view raw hello_for.go hosted with ❤ by GitHub

switch

package main
import "fmt"
func main() {
i := 42
switch i {
case 0:
fmt.Print("case 0")
case 42:
fmt.Println("Hello, 世界")
default:
fmt.Println("default")
}
}
view raw hello_switch.go hosted with ❤ by GitHub

switch with fallthrough

package main
import "fmt"
func main() {
i := 42
switch i {
case 1:
fmt.Print("case 1")
fallthrough
case 42:
fmt.Print("Hello, ")
fallthrough
case 84:
fmt.Print("世")
fallthrough
case 404:
fmt.Println("界")
case 440:
fmt.Println("case 440")
default:
fmt.Println("default")
}
}

switch default

package main
import "fmt"
func main() {
i := 42
switch i {
case 0:
fmt.Println("case 0")
case 1:
fmt.Println("case 1")
default:
fmt.Println("Hello, 世界")
}
}

break in for loop

package main
import "fmt"
func main() {
for i := 0; i < 100; i++ {
if i == 42 {
fmt.Println("Hello, 世界")
break
}
}
}

continue in for loop

package main
import "fmt"
func main() {
for i := 0; i < 100; i++ {
if i != 42 {
continue
}
fmt.Println("Hello, 世界")
}
}

Array

package main
import "fmt"
func main() {
var s = [9]rune{
'H', 'e', 'l', 'l', 'o', ',', ' ', '世', '界',
}
for i := 0; i < len(s); i++ {
fmt.Printf("%c", s[i])
}
fmt.Println()
}
view raw hello_array.go hosted with ❤ by GitHub

Slice

package main
import "fmt"
func main() {
s := make([]rune, 3)
s[0] = 'H'
s[1] = 'e'
s[2] = 'l'
s = append(s, 'l')
s = append(s, 'o', ',', ' ', '世', '界')
fmt.Println(string(s))
}
view raw hello_slice.go hosted with ❤ by GitHub

Channel - Buffered

package main
import "fmt"
func main() {
m := make(chan string, 2)
m <- "Hello, "
m <- "世界"
fmt.Print(<-m)
fmt.Println(<-m)
}

Channel - Unbuffered

package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "Hello, 世界"
}()
fmt.Println(<-ch)
}

function

package main
import (
"fmt"
"log"
)
func helloWorld(s string) (string, error) {
return s, nil
}
func main() {
s, err := helloWorld("Hello, 世界")
if err != nil {
log.Fatal("could not get hello greeting")
}
fmt.Println(s)
}
view raw hello_func.go hosted with ❤ by GitHub

init()

package main
import "fmt"
func init() {
fmt.Print(hello)
}
func init() {
fmt.Println(world)
}
var (
hello = "Hello, "
world = "世界"
)
func main() {
}
view raw hello_init.go hosted with ❤ by GitHub

init() order - multiple files

package main
import "fmt"
func init() {
fmt.Print(hello)
}
var hello = "Hello, "
func main() {
fmt.Println()
}
/*
To Run: go run hello_init.go world_init.go
*/
view raw hello_init.go hosted with ❤ by GitHub

package main
import "fmt"
var world = "世界"
func init() {
fmt.Print(world)
}
view raw world_init.go hosted with ❤ by GitHub

Closure

package main
import "fmt"
func getGreetingByteSeq() func() (byte, bool) {
i := 0
s := "Hello, 世界"
return func() (byte, bool) {
i++
return s[i-1], i == len(s)
}
}
func main() {
getNextByte := getGreetingByteSeq()
s := make([]byte, 0)
b, last := getNextByte()
for {
if last {
s = append(s, b)
break
} else {
s = append(s, b)
b, last = getNextByte()
}
}
fmt.Println(string(s))
}

defer

package main
import "fmt"
func printStr(s string) {
fmt.Print(s)
}
func printHelloWorld() {
defer printStr("界")
defer printStr("世")
defer printStr(", ")
printStr("Hello")
}
func main() {
printHelloWorld()
printStr("\n")
}
view raw hello_defer.go hosted with ❤ by GitHub

Error

package main
import (
"errors"
"fmt"
)
func createError() error {
return errors.New("Hello, 世界")
}
func main() {
err := createError()
if err != nil {
fmt.Println(err)
}
}
view raw hello_errors.go hosted with ❤ by GitHub

Goroutines

package main
import (
"fmt"
)
func greet(c chan string) {
c <- "Hello, 世界"
}
func main() {
c := make(chan string)
go greet(c)
msg := <-c
fmt.Println(msg)
}

Interface

package main
import "fmt"
type greeter interface {
greet() string
}
type gopher struct{}
func (gopher) greet() string {
return "Hello, 世界"
}
func main() {
var g greeter
g = gopher{}
fmt.Println(g.greet())
}

map

package main
import (
"fmt"
"strconv"
)
func main() {
m := make(map[string]rune)
m["key1"] = 'H'
m["key2"] = 'e'
m["key3"] = 'l'
m["key4"] = 'l'
m["key5"] = 'o'
m["key6"] = ','
m["key7"] = ' '
m["key8"] = '世'
m["key9"] = '界'
for _, k := range []int{1, 2, 3, 4, 5, 6, 7, 8, 9} {
key := "key" + strconv.Itoa(k)
fmt.Printf("%c", m[key])
}
fmt.Println()
}
view raw hello_map.go hosted with ❤ by GitHub

Pointers

package main
import "fmt"
func main() {
s := ""
populateHelloWorld(&s)
fmt.Println(s)
}
func populateHelloWorld(sptr *string) {
*sptr = "Hello, 世界"
}

range

package main
import (
"fmt"
)
func main() {
out := "Hello, 世界"
for _, ch := range out {
fmt.Printf("%c", ch)
}
fmt.Println()
}

return

package main
import "fmt"
func getHelloWorld() string {
return "Hello, 世界"
}
func main() {
s := getHelloWorld()
fmt.Println(s)
}
view raw hello_return.go hosted with ❤ by GitHub

struct

package main
import "fmt"
type greet struct {
greeting string
to string
}
func main() {
g := greet{greeting: "Hello", to: "世界"}
fmt.Println(g.greeting + ", " + g.to)
}
view raw hello_struct.go hosted with ❤ by GitHub

struct embedding

package main
import "fmt"
type greet struct {
msg string
}
type gopher struct {
greet
}
func (g greet) sayHelloWorld() {
fmt.Println("Hello, 世界")
}
func main() {
g := gopher{greet: greet{msg: "hello"}}
g.sayHelloWorld()
}

JSON

package main
import (
"encoding/json"
"fmt"
)
type greet struct {
Output string `json:"output"`
}
func main() {
g := greet{Output: "Hello, 世界"}
b, err := json.Marshal(g)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}

UTF-8

package main
import "fmt"
func main() {
h := "Hello"
世界 := "世界"
fmt.Println(h + ", " + 世界)
}
view raw hello_utf8.go hosted with ❤ by GitHub

Variadic arguments

package main
import "fmt"
func main() {
greeting("Hello", ", ", "世", "界")
}
func greeting(h string, to ...string) {
fmt.Print(h)
for _, s := range to {
fmt.Print(s)
}
fmt.Println()
}

String replace

package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("He..o, 世界", ".", "l", -1))
}

Web

package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", helloWorldHandler)
printInstructions()
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
func helloWorldHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, 世界")
}
func printInstructions() {
fmt.Println(`Visit http://localhost:8080 in the web browser to see "Hello, 世界"`)
fmt.Println(`After that Press control+c to stop the server`)
}
view raw hello_web.go hosted with ❤ by GitHub

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs