2015-07-15 09:15

Golang sort.Swap方法

  • IT行业问题
  • 计算机技术
  • it技术
  • 编程语言问答
  • 互联网问答

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?


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dtjxhf595733 dtjxhf595733 6年前

    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 duanguan3863 5年前

    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!

    点赞 评论 复制链接分享