Free GoLang Standard Library Questions and Answers — Questions and Answers
Question 1: Which of the following strings package functions are used to manipulate strings in Go?
- strings.Contains (Correct answer)
- strings.ToUpper (Correct answer)
- strings.Replace (Correct answer)
- strings.Sort
Correct answer: strings.Contains
The `strings` package in Go provides a rich set of functions for string manipulation. `strings.Contains` checks if a substring is present, `strings.ToUpper` converts a string to uppercase, and `strings.Replace` replaces occurrences of a substring. `strings.Sort` is not a function in the `strings` package; sorting is typically done using the `sort` package on slices of strings.
Question 2: Which package is primarily used for file handling in Go?
- io
- os (Correct answer)
- bufio (Correct answer)
- file
Correct answer: os
The `os` package in Go provides a platform-independent interface to operating system functionality, including file and directory operations. While `io` provides basic interfaces for I/O primitives and `bufio` offers buffered I/O, `os` is the primary package for direct file handling like opening, creating, and removing files.
Question 3: Which functions from the encoding/json package are commonly used for JSON encoding and decoding in Go?
- json.Marshal (Correct answer)
- json.Unmarshal (Correct answer)
- json.Encode
- json.Parse
Correct answer: json.Marshal
The `encoding/json` package in Go provides functions for encoding and decoding JSON data. `json.Marshal` is used to encode a Go value into its JSON representation (a byte slice), and `json.Unmarshal` is used to decode JSON data into a Go value. These are the primary functions for converting between Go structs and JSON data.
Question 4: Which functions are used from the net/http package to set up an HTTP server in Go?
- http.ListenAndServe (Correct answer)
- http.HandleFunc (Correct answer)
- http.Serve
- http.RequestHandler
Correct answer: http.ListenAndServe
To set up an HTTP server in Go, `http.ListenAndServe` is commonly used to start the server and listen for incoming requests on a specified address and port. `http.HandleFunc` registers a function to handle requests for a given URL path. Together, these functions form the basic building blocks for a Go HTTP server.
Question 5: Which functions are used from the sort package to sort slices in Go?
- sort.Ints (Correct answer)
- sort.Strings (Correct answer)
- sort.Float64s (Correct answer)
- sort.SortStrings
Correct answer: sort.Ints
The `sort` package in Go provides functions for sorting slices of various types. `sort.Ints` sorts a slice of integers, `sort.Strings` sorts a slice of strings, and `sort.Float64s` sorts a slice of float64s. These specialized functions offer convenient ways to sort common primitive slice types.
Which of the following strings package functions are used to manipulate strings in Go?