25-functions/questions/README.md
func run(p Process, id1, id2 int) (pid int, err error) {}
func add(a, b int) {
return a + b
return
}
2: Actually, it is correct because the func doesn't declare a result value.
3: Correct. It should be:
func add(a, b int) int { return a + b }
func incr(a int) {
a++
return
}
num := 10
// You want it to print 11 but it prints 10 instead.
fmt.Println( incr(num) )
func incr(a int) int { a++; return a } CORRECTfunc incr(a int, newA int) { a++; newA = a }func incr(a int) int { return a++ }1: Go is a 100% pass-by-value language. So, the inputs to a func are local to that function: The changes are not visible outside of that func.
3: It's because: Anyone can access and change them.
// Why this?
func incr(n string) (int, error) {
m, err := strconv.Atoi(n)
return n + 1, err
}
// Instead of this?
func incr(n string) int {
m, _ := strconv.Atoi(n)
return m + 1
}
Atoi returns 0, so you don't need to return an error2: Sometimes, this is partly true however it is better to let the caller know when something goes wrong.
func spread(samples int, P int) (estimated float64) {
for i := 0; i < P; i++ {
estimated += estimate(i, P)
}
return
}
estimated is a named result value. So the naked return returns estimated automatically. CORRECTestimated.IT SHOULD PRINT: map[1:11 10:3]
func main() {
stats := map[int]int{1: 10, 10: 2}
incrAll(stats)
fmt.Print(stats)
}
func incrAll(stats map[int]int) {
for k := range stats {
stats[k]++
}
}
incrAll cannot update the map value.incrAll can update the map value. CORRECT2: Map values are pointers. So,
incrAllcan update the map value.
IT SHOULD PRINT: [10 5 2]
func main() {
stats := []int{10, 5}
add(stats, 2)
fmt.Print(stats)
}
func add(stats []int, n int) {
stats = append(stats, n)
}
add() cannot update the original slice header. CORRECTadd() can add new element to the original slice header.1: Go is a pass-by-value programming language. add() creates a copy of the original slice header and adds the new element to the new slice header but it never returns the updated one. So, it cannot update the original slice header. It should have been returning the original slice header.