Exercises & activities from the go workshop provided by Packt: https://courses.packtpub.com/courses/go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.4 KiB

  1. package main
  2. import "fmt"
  3. func linked() (int, int, int) {
  4. s1 := []int{1, 2, 3, 4, 5}
  5. s2 := s1
  6. s3 := s1[:]
  7. s1[3] = 99
  8. return s1[3], s2[3], s3[3]
  9. }
  10. func noLink() (int, int) {
  11. s1 := []int{1, 2, 3, 4, 5}
  12. s2 := s1
  13. s1 = append(s1, 6)
  14. s1[3] = 99
  15. return s1[3], s2[3]
  16. }
  17. func capLinked() (int, int) {
  18. s1 := make([]int, 5, 10)
  19. s1[0], s1[1], s1[2], s1[3], s1[4] = 1, 2, 3, 4, 5
  20. s2 := s1
  21. s1 = append(s1, 6)
  22. s1[3] = 99
  23. return s1[3], s2[3]
  24. }
  25. func capNoLink() (int, int) {
  26. s1 := make([]int, 5, 10)
  27. s1[0], s1[1], s1[2], s1[3], s1[4] = 1, 2, 3, 4, 5
  28. s2 := s1
  29. s1 = append(s1, []int{10: 11}...)
  30. s1[3] = 99
  31. return s1[3], s2[3]
  32. }
  33. func copyNoLink() (int, int, int) {
  34. s1 := []int{1, 2, 3, 4, 5}
  35. s2 := make([]int, len(s1))
  36. copied := copy(s2, s1)
  37. s1[3] = 99
  38. return s1[3], s2[3], copied
  39. }
  40. func appendNoLink() (int, int) {
  41. s1 := []int{1, 2, 3, 4, 5}
  42. s2 := append([]int{}, s1...)
  43. s1[3] = 99
  44. return s1[3], s2[3]
  45. }
  46. func main() {
  47. l1, l2, l3 := linked()
  48. fmt.Println("Linked: ", l1, l2, l3)
  49. nl1, nl2 := noLink()
  50. fmt.Println("No Link: ", nl1, nl2)
  51. cl1, cl2 := capLinked()
  52. fmt.Println("Cap Linked: ", cl1, cl2)
  53. cn1, cn2 := capNoLink()
  54. fmt.Println("Cap no Link: ", cn1, cn2)
  55. copy1, copy2, copied := copyNoLink()
  56. fmt.Print("Copy No Link: ", copy1, copy2)
  57. fmt.Printf(" (Number of elements copied: %v\n", copied)
  58. a1, a2 := appendNoLink()
  59. fmt.Println("Append No Link: ", a1, a2)
  60. }