如何平方数组中的所有数字?Golang

Ant*_*FSS -3 go

package main

import (
    "fmt"
)

func main() {
    var square int
    box := [4]int{1, -2, 3, 4}

    square = box * *box

    fmt.Println("The square of the first box is", square)
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我正确的方法吗?问题是square的直接无效(type [4] int)

小智 8

你可能想要这样的东西:

package main

import (
  "fmt"
)

func main() {
  box := []int{1, -2, 3, 4}
  square := make([]int, len(box))
  for i, v := range box {
    square[i] = v*v
  }

  fmt.Println("The square of the first box is ", square)
}
Run Code Online (Sandbox Code Playgroud)