猿问

没有返回值的Go函数如何修改数据?

我不明白 bubbleSort() 切片如何a应用于 main() 。


我不给出return a也不写全局变量。


package main


import (

    "fmt"

)


func bubbleSort(a []int) {

    var temp int

    for j := 0; j < len(a); j++ {

        for i := 0; i < (len(a) - 1); i++ {

            if a[i] > a[i+1] {

                temp = a[i]

                a[i] = a[i+1]

                a[i+1] = temp

            }

        }

    }

}


func inputNums() []int {

    var input int

    var number int


    fmt.Scan(&input)

    s := make([]int, input)


    for i := 0; i < input; i++ {

        fmt.Scan(&number)

        s[i] = number

    }

    return s

}


func outputNums(b []int) {

    for i := 0; i < len(b); i++ {

        fmt.Print(b[i])

        fmt.Print(" ")

    }

}


func main() {

    nums := inputNums()

    bubbleSort(nums)

    outputNums(nums)

}


慕桂英546537
浏览 92回答 1
1回答

一只斗牛犬

src/runtime/slice.gotype slice struct {&nbsp; array unsafe.Pointer&nbsp; len&nbsp; &nbsp;int&nbsp; cap&nbsp; &nbsp;int}在 Go 中,所有参数都是按值传递的。切片描述符是一个结构体,通过值传递,就像通过赋值一样。切片描述符包含指向其底层数组的指针。func bubbleSort(a []int)按值接收a参数,但使用指针a.array修改底层数组元素。
随时随地看视频慕课网APP

相关分类

Go
我要回答