Consider the following Go code that tries to open a file and returns an error if it fails. What will be printed when the file does not exist?
package main import ( "fmt" "os" ) func openFile(filename string) error { _, err := os.Open(filename) return err } func main() { err := openFile("nonexistent.txt") if err != nil { fmt.Println("Error occurred:", err) } else { fmt.Println("File opened successfully") } }
Think about what happens when os.Open tries to open a file that does not exist.
The os.Open function returns an error if the file does not exist. The error is returned by openFile and checked in main. Since the file "nonexistent.txt" does not exist, the error is not nil, so the error message is printed.
Look at this Go function that returns an error. What will be the output when calling checkValue(5)?
package main import ( "errors" "fmt" ) func checkValue(x int) error { if x < 10 { return errors.New("value too small") } return nil } func main() { err := checkValue(5) if err != nil { fmt.Println(err.Error()) } else { fmt.Println("Value is fine") } }
Check the condition inside checkValue and what error is returned.
The function returns an error with the message "value too small" if the input is less than 10. Since 5 is less than 10, the error is returned and printed.
Identify which code snippet will cause a compile-time error because it returns a wrong type instead of an error.
Remember that the function must return a value of type error.
Option A returns a string instead of an error type, causing a compile-time type mismatch error. The other options correctly return error or nil.
Consider this Go code that wraps an error. What will be printed?
package main import ( "errors" "fmt" ) func inner() error { return errors.New("inner error") } func outer() error { return fmt.Errorf("outer error: %w", inner()) } func main() { err := outer() fmt.Println(err.Error()) }
Look at how %w is used in fmt.Errorf.
The %w verb wraps the inner error inside the outer error message. So the printed message includes both errors.
Analyze this Go code with a custom error type implementing the error interface. What will be printed?
package main import ( "fmt" ) type MyError struct { Code int Msg string } func (e *MyError) Error() string { return fmt.Sprintf("Error %d: %s", e.Code, e.Msg) } func doTask(fail bool) error { if fail { return &MyError{Code: 404, Msg: "Not Found"} } return nil } func main() { err := doTask(true) if err != nil { switch e := err.(type) { case *MyError: fmt.Println("Custom error detected:", e.Error()) default: fmt.Println("Other error:", err.Error()) } } else { fmt.Println("Task succeeded") } }
Check how the type assertion works with the custom error type.
The error returned is of type *MyError. The type switch detects this and prints the custom message with code and text.