Files
learngo/16-slices/exercises/23-limit-the-backing-array-sharing/main.go

74 lines
1.9 KiB
Go
Raw Normal View History

2019-03-04 20:30:18 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
2019-03-05 23:32:32 +03:00
"github.com/inancgumus/learngo/16-slices/exercises/23-limit-the-backing-array-sharing/api"
2019-03-04 20:30:18 +03:00
)
// ---------------------------------------------------------
// EXERCISE: Limit the backing array sharing
//
2019-08-22 20:00:58 +03:00
// In this exercise: API means the api package. It's in the
// api folder.
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// `Read` function of the api package returns a portion of
// a slice. The main function [main()] below uses the
// Read function.
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// `main()` appends to the slice but doing so changes the
// backing array of the api package's temps slice as well.
// We don't want that.
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// Only allow `main()` to change the part of the slice
// it receives from the Read function.
2019-08-18 12:59:50 +03:00
//
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// NOTE
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// You need to import the api package.
2019-03-04 20:30:18 +03:00
//
//
2019-08-18 12:59:50 +03:00
// CURRENT
2019-03-04 20:30:18 +03:00
//
// | |
2019-08-18 12:59:50 +03:00
// v v
// api.temps : [5 10 3 1 3 80 90]
// main.temps : [5 10 3 1 3]
// ^ ^ append changes the api package's
2019-08-22 20:00:58 +03:00
// temps slice's backing array.
2019-08-18 12:59:50 +03:00
//
2019-03-04 20:30:18 +03:00
//
//
2019-08-18 12:59:50 +03:00
// EXPECTED
2019-03-04 20:30:18 +03:00
//
2019-08-22 20:00:58 +03:00
// The corrected api package does not allow the `main()` change
// the api package's temps slice's backing array.
2019-03-04 20:30:18 +03:00
// | |
2019-08-18 12:59:50 +03:00
// v v
// api.temps : [5 10 3 25 45 80 90]
// main.temps : [5 10 3 1 3]
2019-03-04 20:30:18 +03:00
//
// ---------------------------------------------------------
func main() {
2019-08-22 20:00:58 +03:00
// DO NOT CHANGE ANYTHING IN THIS CODE.
2019-03-04 20:30:18 +03:00
2019-08-18 12:59:50 +03:00
// get the first three elements from api.temps
2019-08-22 20:00:58 +03:00
slice := api.Read(0, 3)
2019-03-04 20:30:18 +03:00
2019-08-22 20:00:58 +03:00
// append changes the api package's temps slice's
// backing array as well.
slice = append(slice, []int{1, 3}...)
2019-03-04 20:30:18 +03:00
2019-08-18 12:59:50 +03:00
fmt.Println("api.temps :", api.All())
2019-08-22 20:00:58 +03:00
fmt.Println("main.slice :", slice)
2019-03-04 20:30:18 +03:00
}