【问题标题】:Merge two arrays in Go... container assign error在 Go 中合并两个数组...容器分配错误
【发布时间】:2026-01-13 21:20:05
【问题描述】:

我今天早上都在试图找出我的代码出了什么问题,但没有。它说它不能分配容器。请检查这个去游乐场http://play.golang.org/p/RQmmi7nJAK

下面是有问题的代码。

 func My_Merge(container []int, first_index int, mid_index int, last_index int) {
      left_array := make([]int, mid_index-first_index+1)
      right_array := make([]int, last_index-mid_index)
      temp_i := 0
      temp_j := 0

      for i := first_index; i < mid_index; i++ {
           left_array[temp_i] = container[i]
           temp_i++
      }

      for j := mid_index; j < last_index+1; j++ {
           right_array[temp_j] = container[j]
           temp_j++
      }

      i := 0
      j := 0

      for elem := first_index; elem < len(container); elem++ {
           if left_array[i] <= right_array[j] {
                container[elem] = left_array[i]
                i++
                if i == len(left_array) {
                     container[elem+1:last_index] = right_array[j:]
                     break              
                }           
           } else {
                container[elem] = right_array[j]
                j++
                if j == len(right_array) {
                     container[elem+1:last_index] = left_array[i:]
                     break              
                }
           }
      }
 }

我在行 container[elem+1:last_index] = right_array[j:] 中遇到错误。 即使我删除了整个块,我也会收到错误。有人可以帮我吗?我将不胜感激。

【问题讨论】:

    标签: arrays sorting merge go mergesort


    【解决方案1】:

    您不能在 Go 中分配给切片表达式。您需要使用副本:

    copy(container[elem+1:last_index], right_array[j:])
    

    但显然还有其他问题,因为当我在操场上更改它时,我得到一个索引超出范围错误。

    【讨论】:

      最近更新 更多