•  


Go by Example: Arrays

Go by Example : Arrays

In Go, an array is a numbered sequence of elements of a specific length. In typical Go code, slices are much more common; arrays are useful in some special scenarios.

package
 main
import
 "fmt"
func
 main
()
 {

Here we create an array a that will hold exactly 5 int s. The type of elements and length are both part of the array’s type. By default an array is zero-valued, which for int s means 0 s.

    var
 a
 [
5
]
int

    fmt
.
Println
(
"emp:"
,
 a
)

We can set a value at an index using the array[index] = value syntax, and get a value with array[index] .

    a
[
4
]
 =
 100

    fmt
.
Println
(
"set:"
,
 a
)

    fmt
.
Println
(
"get:"
,
 a
[
4
])

The builtin len returns the length of an array.

    fmt
.
Println
(
"len:"
,
 len
(
a
))

Use this syntax to declare and initialize an array in one line.

    b
 :=
 [
5
]
int
{
1
,
 2
,
 3
,
 4
,
 5
}

    fmt
.
Println
(
"dcl:"
,
 b
)

You can also have the compiler count the number of elements for you with ...

    b
 =
 [
...
]
int
{
1
,
 2
,
 3
,
 4
,
 5
}

    fmt
.
Println
(
"dcl:"
,
 b
)

If you specify the index with : , the elements in between will be zeroed.

    b
 =
 [
...
]
int
{
100
,
 3
:
 400
,
 500
}

    fmt
.
Println
(
"idx:"
,
 b
)

Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.

    var
 twoD
 [
2
][
3
]
int

    for
 i
 :=
 0
;
 i
 <
 2
;
 i
++
 {

        for
 j
 :=
 0
;
 j
 <
 3
;
 j
++
 {

            twoD
[
i
][
j
]
 =
 i
 +
 j

        }

    }

    fmt
.
Println
(
"2d: "
,
 twoD
)

You can create and initialize multi-dimensional arrays at once too.

    twoD
 =
 [
2
][
3
]
int
{

        {
1
,
 2
,
 3
},

        {
1
,
 2
,
 3
},

    }

    fmt
.
Println
(
"2d: "
,
 twoD
)

}

Note that arrays appear in the form [v1 v2 v3 ...] when printed with fmt.Println .

$
 go run arrays.go
emp: [0 0 0 0 0]
set: [0 0 0 0 100]
get: 100
len: 5
dcl: [1 2 3 4 5]
dcl: [1 2 3 4 5]
idx: [100 0 0 400 500]
2d:  [[0 1 2] [1 2 3]]
2d:  [[1 2 3] [1 2 3]]

Next example: Slices .

- "漢字路" 한글한자자동변환 서비스는 교육부 고전문헌국역지원사업의 지원으로 구축되었습니다.
- "漢字路" 한글한자자동변환 서비스는 전통문화연구회 "울산대학교한국어처리연구실 옥철영(IT융합전공)교수팀"에서 개발한 한글한자자동변환기를 바탕하여 지속적으로 공동 연구 개발하고 있는 서비스입니다.
- 현재 고유명사(인명, 지명등)을 비롯한 여러 변환오류가 있으며 이를 해결하고자 많은 연구 개발을 진행하고자 하고 있습니다. 이를 인지하시고 다른 곳에서 인용시 한자 변환 결과를 한번 더 검토하시고 사용해 주시기 바랍니다.
- 변환오류 및 건의,문의사항은 juntong@juntong.or.kr로 메일로 보내주시면 감사하겠습니다. .
Copyright ⓒ 2020 By '전통문화연구회(傳統文化硏究會)' All Rights reserved.
 한국   대만   중국   일본