This quiz gives you 10 small problems to solve. Most of them are about finding error in code without running it. Like what we do during code reviews. You score will be shown to you immediately after submitting the answers. No pressure: take your time and and retry as many times as you want.
If you like it, consider to follow @dailygolangquiz.
Without running the code below, can you say what will be its output? (hint: smile is unicode character 0x1F604)
package main
import "fmt"
func main() {
fmt.Println(len("😄"))
}
Answer:
Without running the code below, can you say what will be its output?
package main
import "fmt"
func main() {
s := 0
for i := range []int{1, 2} {
s += i
}
fmt.Println(s)
}
Answer:
The code below contains one error, which makes it print 0 instead of 1. What should be added in order to make it work? (hint: single character)
package main
import "fmt"
type Container struct {
Value int
}
func (c Container) SetValue(value int) {
c.Value = value
}
func main() {
c := Container{}
c.SetValue(1)
fmt.Println(c.Value)
}
Answer:
It is nice to provide a corresponding error code when the program terminates with an error. What should be written instead of /* code */ to return the code 10 in case of failure?
package main
import (
"io/ioutil"
"os"
)
func main() {
_, err := ioutil.ReadFile(os.Getenv("USER_PROFILE_DIR") + "/test.txt")
if err != nil {
/* code */
}
}
Answer:
The code below creates file incorrectly sometimes. What should be replaced to make it right? (hint: works well on windows)
{{data.q05.code}}
Answer:
The code below contains case-sensitive regexp. Could you please write case-insensitive instead?
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("go")
fmt.Println(re.MatchString("GO"), re.MatchString("go"))
}
Answer:
What keyword should the /* keyword */ comment be replaced with to print " ok google"?
package main
import "fmt"
func main() {
say := 1
switch say {
case 1: fmt.Printf(" ok"); /* keyword */
case 2: fmt.Printf(" google")
}
}
Answer:
Try to answer without running the code, what will be its output? (hint: this is little-endian question)
package main
import (
"fmt"
"unsafe"
)
func main() {
v := 0x0102
*(*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + 1)) = 0
fmt.Println(v)
}
Answer:
The code below prints "1 false". Apparently, the "true" case is selected even though `ok` is false. What should be added to select the correct case?
package main
import (
"fmt"
)
func main() {
switch ok := false; {
case true:
fmt.Println("1", ok)
case false:
fmt.Println("0", ok)
}
}
Answer:
What should be import in the code below in order to make it work? (hint: Dir is from "path/filepath")
package main
import ( /* imports */ )
func main() {
Println(fp.Dir("/home/user"))
}
Answer: