这几天ChatGPT突然之间火得一塌糊涂。这个AI能够写小说、剧本、散文,回答各种问题,当然它肯定也能写代码,还能扮演Linux虚拟机来执行各种命令、编译代码。由于它过于强大,有人用它来回答stackoverflow上的各种问题,导致官方采取临时措施,把这个AI给禁止了。不得不说,它回答这些问题比google要好用多了。

我也折腾了一个账号,上去试了试。作为程序员,我让ChatGPT用Go写了段快速排序的代码,总体看起来还是很不错的:

func quickSort(arr []int) []int {
  // base case: if the length of the array is 0 or 1, it is already sorted
  if len(arr) < 2 {
    return arr
  }

  // choose the pivot element as the middle element of the array
  pivot := arr[len(arr) / 2]

  // create two empty slices for the elements that are less than and greater than the pivot
  less := []int{}
  greater := []int{}

  // partition the other elements into the two slices
  for i := range arr {
    if i != len(arr) / 2 {
      if arr[i] < pivot {
        less = append(less, arr[i])
      } else {
        greater = append(greater, arr[i])
      }
    }
  }

  // sort the two slices recursively and concatenate them with the pivot in between
  return append(quickSort(less), pivot, quickSort(greater)...)
}

然而遗憾的是,最后一行代码并不能通过编译。这个三个点的省略号用法似乎在理解上有一些问题,我也看到有一些说法是这个语法糖是把数组打散成单个元素作为参数传入,其实这个理解是不正确的。在Go官方文档中是这样写的:

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

...T是会被当做[]T来处理的,因此在append这个函数中,要么传入多个T,要么传入一个[]T,而不能两者混用。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.