2015-07-15 09:15
浏览 197

Golang sort.Swap方法

I am fairly new to Golang, although I have already written some lines of code. I was exploring the sorting options when I found this(src):

func (p StringSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

I have no clue what is it going on there. Could someone explain to me what p[i], p[j] = p[j], p[i] is doing?


图片转代码服务由CSDN问答提供 功能建议

我对Golang还是陌生的,尽管我已经写了一些代码行。 当我发现此 (src )

  func(p StringSlice)Swap(i,j int){p [i],p [j] = p [j  ],p [i]} 

我不知道那是怎么回事。 有人可以向我解释 p [i],p [j] = p [j],p [i] 在做什么?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtjxhf595733 2015-07-15 09:19

    It does what its name says: it swaps the ith and jth elements.

    It is an assignment, more specifically a tuple assignment:

    p[i], p[j] = p[j], p[i]

    It assigns values to p[i] and p[j], and the values that are assigned to them in order are p[j] and p[i].

    The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.

    点赞 评论
  • duanguan3863 2016-06-23 08:21

    here in golang, we dont need a tmp variable. It will assign directly with line p[i], p[j] = p[j], p[i]

    it is one of miracles in golang Enjoy!

    点赞 评论

相关推荐 更多相似问题