2017-03-02 200 views
-2

我是編程初學者。我可以在golang for-loops中使用兩個元素嗎?如果您知道我應該閱讀的答案或材料,請幫助我。我如何改進代碼?

package main 

import (
    "fmt" 
) 

func main() { 
    x := []int{ 
     48, 96, 86, 68, 
     57, 82, 63, 70, 
     37, 34, 83, 27, 
     19, 97, 9, 17, 
    } 

    for a := 0, b := 1; a++, b++ { 
     if x[a] > x[b] { 
      x = append(x[:1], x[1+1:]...) 
      fmt.Println("x[1+1:]x)", x) 
     } else { 
      x = append(x[:0], x[0+1:]...) 
      fmt.Println("x[0+1:]x)", x) 
     } 
    } 

} 
+1

Golang for循環:https://golang.org/doc/effective_go.html#for – jrahhali

+1

是的,你可以。您的語法錯誤請參閱https://golang.org/doc/effective_go.html#for –

回答

0

是的,你可以,雖然在這種情況下沒有必要。

syntax函數修復代碼中的語法和其他錯誤,以便代碼運行並生成輸出。 idiom函數以更習慣的形式重寫您的代碼。

package main 

import (
    "fmt" 
) 

func syntax() { 
    x := []int{ 
     48, 96, 86, 68, 
     57, 82, 63, 70, 
     37, 34, 83, 27, 
     19, 97, 9, 17, 
    } 

    for a, b := 0, 1; a < len(x) && b < len(x); a, b = a+1, b+1 { 
     if x[a] > x[b] { 
      x = append(x[:1], x[1+1:]...) 
      fmt.Println("x[1+1:]x)", x) 
     } else { 
      x = append(x[:0], x[0+1:]...) 
      fmt.Println("x[0+1:]x)", x) 
     } 
    } 
} 

func idiom() { 
    x := []int{ 
     48, 96, 86, 68, 
     57, 82, 63, 70, 
     37, 34, 83, 27, 
     19, 97, 9, 17, 
    } 

    for i := 1; i < len(x); i++ { 
     if x[i-1] > x[i] { 
      x = append(x[:1], x[1+1:]...) 
      fmt.Println("x[1+1:]x)", x) 
     } else { 
      x = append(x[:0], x[0+1:]...) 
      fmt.Println("x[0+1:]x)", x) 
     } 
    } 
} 

func main() { 
    syntax() 
    fmt.Println() 
    idiom() 
} 

輸出:

$ go run beginner.go 
x[0+1:]x) [96 86 68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [96 68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [57 82 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [57 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [57 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [37 34 83 27 19 97 9 17] 

x[0+1:]x) [96 86 68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [96 68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [68 57 82 63 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [57 82 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [57 63 70 37 34 83 27 19 97 9 17] 
x[1+1:]x) [57 70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [70 37 34 83 27 19 97 9 17] 
x[0+1:]x) [37 34 83 27 19 97 9 17] 

按照採取A Tour of Go的鏈接。

+0

WOW !.非常感謝你!這很棒... –