select
package main
import "sync"
func main() {
var wg sync.WaitGroup
foo := make(chan int)
bar := make(chan int)
wg.Add(1)
go func() {
defer wg.Done()
select {
case foo <- <-bar:
default:
println("default")
}
}()
wg.Wait()
}
Answer
Try it
fatal error: all goroutines are asleep - deadlock!
select1
package main
import "fmt"
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
ch1 <- 1
}()
go func() {
select {
case <-ch1:
case ch2 <- 2:
}
}()
fmt.Println(<-ch2)
}
- A. 1
- B. 2
- C. No output, program is deadlocked
- D. No output, program has finished execution.
- E. else
Answer
Try it
B
slice
package main
import (
"fmt"
)
func main() {
var s1 []int
var s2 = []int{}
if __ == nil {
fmt.Println("nil slice")
}
if __ != nil {
fmt.Println("empty slice")
}
}
- A. s1, s2
- B. s2, s1
- C. s1, s1
- D. s2, s2
Answer
Try it
A
slice1
package main
import (
"fmt"
)
func main() {
s := [3]int{1, 2, 3}
a := s[:0]
b := s[:2]
c := s[1:2:cap(s)]
fmt.Println(len(a), cap(a))
fmt.Println(len(b), cap(b))
fmt.Println(len(c), cap(c))
}
Answer
Try it
0 3
2 3
1 2
slice2
package main
import "fmt"
func main() {
s1 := []int{1, 2, 3}
s2 := s1[1:]
s2[1] = 4
fmt.Println(s1)
s2 = append(s2, 5, 6, 7)
fmt.Println(s1)
}
Answer
Try it
[1 2 4]
[1 2 4]
variable
- A. p.name
- B. (&p).name
- C. (*p).name
- D. p->name
Answer
AC
variable1
package main
import (
"fmt"
)
func main() {
var ans float64 = 15 + 25 + 5.2
fmt.Println(ans)
}
- A. 45
- B. 45.0
- C. 45.2
- D. compliation error
Answer
Try it
C
variable2
package main
import (
"fmt"
)
func main() {
var ans float64 = 3 / 2
fmt.Println(ans)
}
- A. 1.5
- B. 1
- C. 0
- D. compliation error
Answer
Try it
B
variable3
package main
func main() {
const a int8 = -1
var b int8 = -128 / a
println(b)
}
Answer
Try it
compliation error
-128 / a (constant 128 of type int8) overflows int8
variable4
package main
func main() {
var a int8 = -1
var b int8 = -128 / a
println(b)
}
Answer
Try it
-128
variable5
package main
import "fmt"
type MyInt1 int
type MyInt2 = int
func main() {
var i int =0
var i1 MyInt1 = i
var i2 MyInt2 = i
fmt.Println(i1, i2)
}
Answer
Try it
compilation error
cannot use i (variable of type int) as MyInt1 value in variable declaration
variable6
package main
import "fmt"
func main() {
const X = 7.0
var x interface{} = X
if y, ok := x.(int); ok {
fmt.Println(y)
} else {
fmt.Println(int(y))
}
}
- A. 7
- B. 7.0
- C. 0
- D. compilation error
Answer
Try it
C