Go Multiple Choice Questions and answers
We intend to study this using a tiny programme based on Go generics, which was introduced in version 1.18, as is well known. It is initially advised to install the most recent Go build from the official website; otherwise, you can utilise Go Playground.
These multiple-choice questions allow us to understand the fundamentals of going generic; we hope to provide more generics-based questions in the near future.
These multiple-choice questions allow us to understand the fundamentals of going generic; we hope to provide more generics-based questions in the near future.
1. what is the output of below code snippet
package main
import "fmt"
func main() {
fmt.Println("Hello " + "World")
}
2. what is the output of below code snippet
package main
import "fmt"
func sum[int, int Number](a, b Number) Number {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
}
3. what is the output of below code snippet
package main
import "fmt"
func sum[int Number](a, b Number) Number {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
}
4. What is the output of below code snippet?
package main
import "fmt"
func sum(a, b any) any {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
}
5. What is the output of below code snippet?
package main
import "fmt"
type Number interface {
int
}
func sum[T Number](a, b Number) T {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
}
6. What is the output of below code snippet?
package main
import "fmt"
type Number interface {
int
}
func sum[T Number](a, b T) T {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
}
7. What is the output of below code snippet?
package main
import "fmt"
type Number interface {
int
}
func sum[T Number](a, b Number) T {
return a + b
}
func main() {
fmt.Println(sum(2, 3))
fmt.Println(sum(2.1, 3.1))
}
2 Comments
7th one is wrong.
ReplyDelete7th is wrong
ReplyDelete./prog.go:9:25: cannot use type Number outside a type constraint: interface contains type constraints
./prog.go:10:9: invalid operation: operator + not defined on a (variable of type Number)
./prog.go:15:18: cannot use 2.1 (constant of type float64) as type Number in argument to sum:
float64 does not implement Number (float64 missing in int)
./prog.go:15:23: cannot use 3.1 (constant of type float64) as type Number in argument to sum:
float64 does not implement Number (float64 missing in int)