SquareOrSquareRoot should get an array of integers and return a new array. If the number at index i is a "square" number the returned array at index i should have its square root. If the original number is not a "square" number then the returned array in index i should be the number squared.

Coming from Python (where this could be done in a single line using list comprehension or using map), I find it very odd that this is probably one of the shortest ways to achieve that in Go (please prove me wrong).

package main

import (

func SquareOrSquareRoot(arr []int) []int{
    arr_to_return := make([]int, len(arr))
    for index, value := range arr {
        val_sqrt := math.Sqrt(float64(value))
        if val_sqrt == math.Trunc(val_sqrt) {
            arr_to_return[index] = int(val_sqrt)
        } else {
            arr_to_return[index] = value * value

    return arr_to_return

func main() {
    arr := []int{100, 101, 5, 5, 1, 1}
    // [10 10201 25 25 1 1]

1 Answer 1


Naming conventions aside (short names in camelCase are typically used in Go), this is the right way of doing what you want. The authors of Go have a different view of what is more readable & maintainable than the authors of Python :-)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.