diff options
| -rw-r--r-- | content/basics.article | 195 | ||||
| -rw-r--r-- | content/concurrency.article | 210 | ||||
| -rw-r--r-- | content/flowcontrol.article | 200 | ||||
| -rw-r--r-- | content/methods.article | 424 | ||||
| -rw-r--r-- | content/moretypes.article | 317 | ||||
| -rw-r--r-- | content/welcome.article | 136 | ||||
| -rw-r--r-- | static/js/values.js | 48 |
7 files changed, 847 insertions, 683 deletions
diff --git a/content/basics.article b/content/basics.article index 082a6ab..04cb75e 100644 --- a/content/basics.article +++ b/content/basics.article @@ -1,131 +1,141 @@ -Packages, variables, and functions. -Learn the basic components of any Go program. +Paket, variabel, dan fungsi. +Belajar komponen dasar dari program Go. -The Go Authors +Para Penggubah Go https://golang.org -* Packages +* Paket -Every Go program is made up of packages. +Setiap program Go terbuat dari paket-paket (`package`). -Programs start running in package `main`. +Program mulai berjalan dalam paket `main`. -This program is using the packages with import paths `"fmt"` and `"math/rand"`. +Program ini menggunakan paket dengan meng-`import` `"fmt"` dan `"math/rand"`. -By convention, the package name is the same as the last element of the import path. For instance, the `"math/rand"` package comprises files that begin with the statement `package`rand`. +Aturannya, nama paket sama dengan elemen terakhir dari path `import`. +Sebagai contohnya, paket `"math/rand"` terdiri dari berkas-berkas yang dimulai dengan perintah `package`rand`. -#appengine: *Note:* The environment in which these programs are executed is -#appengine: deterministic, so each time you run the example program -#appengine: `rand.Intn` will return the same number. +#appengine: *Catatan:* Lingkungan di mana program di situs ini berjalan adalah +#appengine: deterministik, sehingga setiap kali anda mengeksekusi contoh +#appengine: program `rand.Intn` akan selalu mengembalikan angka yang sama. #appengine: -#appengine: (To see a different number, seed the number generator; see [[https://golang.org/pkg/math/rand/#Seed][`rand.Seed`]]. -#appengine: Time is constant in the playground, so you will need to use something else as the seed.) +#appengine: (Untuk mendapatkan angka yang acak, tambahkan pembangkit angka; +#appengine: lihat #appengine: [[https://golang.org/pkg/math/rand/#Seed][`rand.Seed`]] .) .play basics/packages.go -* Imports +* Import -This code groups the imports into a parenthesized, "factored" import statement. +Kode ini mengelompokan `import` di dalam tanda kurung, atau disebut juga perintah `import` yang "difaktorkan". -You can also write multiple import statements, like: +Anda juga bisa menulis perintah `import`, seperti: import "fmt" import "math" -But it is good style to use the factored import statement. +Tapi lebih baik menggunakan perintah import yang difaktorkan. .play basics/imports.go -* Exported names +* Nama-nama yang diekspor -In Go, a name is exported if it begins with a capital letter. -For example, `Pizza` is an exported name, as is `Pi`, which is exported from -the `math` package. +Pada bahasa Go, sebuah nama diekspor jika diawali dengan huruf besar. +Sebagai contohnya, `Pizza` itu nama yang diekspor, sebagaimana juga `Pi`, yang +diekspor dari paket `math`. -`pizza` and `pi` do not start with a capital letter, so they are not exported. +`pizza` dan `pi` tidak diawali dengan huruf besar, maka mereka tidak diekspor. -When importing a package, you can refer only to its exported names. -Any "unexported" names are not accessible from outside the package. +Saat mengimpor sebuah paket, anda hanya bisa mengacu pada nama yang diekspor. +Setiap nama yang tidak diekspor tidak akan bisa diakses dari luar paket. -Run the code. Notice the error message. +Jalankan kode disebelah. +Perhatikan akan adanya pesan kesalahan. -To fix the error, rename `math.pi` to `math.Pi` and try it again. +Untuk memperbaikinya, ganti nama `math.pi` dengan `math.Pi` dan coba kembali. .play basics/exported-names.go -* Functions +* Fungsi -A function can take zero or more arguments. +Sebuah fungsi bisa tanpa argumen atau banyak argumen. -In this example, `add` takes two parameters of type `int`. +Pada contoh ini, `add` memiliki dua parameter dengan tipe `int`. -Notice that the type comes _after_ the variable name. +Perhatikan bahwa tipe berada _setelah_ nama variabel. -(For more about why types look the way they do, see the [[https://blog.golang.org/gos-declaration-syntax][article on Go's declaration syntax]].) +(Untuk mengetahui kenapa tipe ditulis seperti itu, lihat +[[https://blog.golang.org/gos-declaration-syntax][artikel Go tentang deklarasi sintaks]].) .play basics/functions.go -* Functions continued +* Fungsi lanjutan -When two or more consecutive named function parameters share a type, you can omit the type from all but the last. +Saat dua atau lebih parameter fungsi memiliki tipe yang sama, anda bisa menghilangkan semua tipe kecuali yang terakhir. -In this example, we shortened +Pada contoh ini, kita singkat x int, y int -to +menjadi x, y int .play basics/functions-continued.go -* Multiple results +* Banyak Kembalian -A function can return any number of results. +Sebuah fungsi dapat mengeluarkan banyak kembalian. -The `swap` function returns two strings. +Fungsi `swap` mengembalikan dua `string`. .play basics/multiple-results.go -* Named return values +* Kembalian bernama -Go's return values may be named. If so, they are treated as variables defined at the top of the function. +Nilai kembalian pada Go bisa dinamakan. +Jika nilai kembalian memiliki nama, mereka diperlakukan seperti variabel yang +didefinisikan pada fungsi. -These names should be used to document the meaning of the return values. +Penamaan tersebut seharusnya digunakan untuk mendokumentasikan makna dari +nilai kembalian. -A `return` statement without arguments returns the named return values. This is known as a "naked" return. +Sebuah perintah `return` tanpa kembalian mengembalikan nilai sekarang dari +setiap variabel kembalian. +Hal ini dikenal dengan kembalian "naked". -Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions. +Perintah kembalian "naked" sebaiknya hanya digunakan pada fungsi yang singkat, +seperti pada contoh di sebelah, karena bisa mengganggu pembacaan kode +bila digunakan pada fungsi yang panjang. .play basics/named-results.go -* Variables +* Variabel -The `var` statement declares a list of variables; as in function argument lists, the type is last. +Perintah `var` mendeklarasikan daftar variabel; seperti pada daftar argumen pada fungsi, tipenya berada di akhir. -A `var` statement can be at package or function level. We see both in this example. +Perintah `var` bisa ditulis pada tingkat paket atau fungsi, seperti pada contoh sebelah. .play basics/variables.go -* Variables with initializers +* Variabel dengan inisialisasi -A var declaration can include initializers, one per variable. +Deklarasi sebuah variabel bisa mengikutkan inisialisasi, satu per variabel. -If an initializer is present, the type can be omitted; the variable will take the type of the initializer. +Jika sebuah inisialisasi ada, maka tipe bisa dihilangkan; variabel akan memiliki tipe dari inisialisasi. .play basics/variables-with-initializers.go -* Short variable declarations +* Deklarasi variabel singkat -Inside a function, the `:=` short assignment statement can be used in place of a `var` declaration with implicit type. +Dalam sebuah fungsi, perintah singkat `:=` bisa digunakan menggantikan `var` dengan tipe implisit. -Outside a function, every statement begins with a keyword (`var`, `func`, and so on) and so the `:=` construct is not available. +Di luar sebuah fungsi, setiap perintah harus dimulai dengan kata kunci (`var`, `func`, dst), sehingga `:=` tidak bisa digunakan. .play basics/short-variable-declarations.go -* Basic types +* Tipe dasar -Go's basic types are +Tipe dasar pada Go yaitu, bool @@ -134,102 +144,103 @@ Go's basic types are int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr - byte // alias for uint8 + byte // alias untuk uint8 - rune // alias for int32 - // represents a Unicode code point + rune // alias untuk int32 + // merepresentasikan sebuah kode Unicode float32 float64 complex64 complex128 -The example shows variables of several types, -and also that variable declarations may be "factored" into blocks, -as with import statements. +Contoh sebelah memperlihatkan variabel dengan beberapa tipe, dan juga deklarasi variabel bisa "difaktorkan" ke dalam blok, seperti pada perintah `import`. -The `int`, `uint`, and `uintptr` types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. -When you need an integer value you should use `int` unless you have a specific reason to use a sized or unsigned integer type. +Tipe `int`, `uint`, dan `uintptr` biasanya memiliki panjang 32 bits pada sistem 32-bit dan 64 bits pada sistem 64-bit. +Saat anda membutuhkan nilai integer anda sebaiknya menggunakan tipe `int` kecuali anda memiliki alasan tertentu menggunakan tipe berukuran khusus atau _unsigned_integer_. .play basics/basic-types.go -* Zero values +* Nilai kosong -Variables declared without an explicit initial value are given their -_zero_value_. +Variabel yang dideklarasikan tanpa nilai awal diberikan _nilai_kosong_. -The zero value is: +Nilai kosong adalah: -- `0` for numeric types, -- `false` for the boolean type, and -- `""` (the empty string) for strings. +- `0` untuk tipe numerik, +- `false` untuk tipe boolean, dan +- `""` (string kosong) untuk string. .play basics/zero.go -* Type conversions +* Konversi Tipe -The expression `T(v)` converts the value `v` to the type `T`. +Ekspresi `T(v)` mengkonversi nilai `v` ke tipe `T`. -Some numeric conversions: +Beberapa konversi numerik: var i int = 42 var f float64 = float64(i) var u uint = uint(f) -Or, put more simply: +Atau, sederhananya: i := 42 f := float64(i) u := uint(f) -Unlike in C, in Go assignment between items of different type requires an -explicit conversion. -Try removing the `float64` or `uint` conversions in the example and see what happens. +Tidak seperti C, perintah pengisian nilai pada Go antara item dengan tipe +berbeda membutuhkan konversi eksplisit. +Coba hilangkan konversi `float64` atau `int` pada contoh sebelah dan lihat apa +yang terjadi. .play basics/type-conversions.go -* Type inference +* Inferensi tipe -When declaring a variable without specifying an explicit type (either by using the `:=` syntax or `var`=` expression syntax), the variable's type is inferred from the value on the right hand side. +Saat mendeklarasikan sebuah variabel tanpa menentukan tipe eksplisitnya (baik menggunakan sintaks `:=` atau `var`), tipe variabel disamakan dengan nilai di sebelah kanannya. -When the right hand side of the declaration is typed, the new variable is of that same type: +Bila sisi kanan dari deklarasi ditulis tipenya, maka variabel baru memiliki tipe yang sama: var i int j := i // j is an int -But when the right hand side contains an untyped numeric constant, the new variable may be an `int`, `float64`, or `complex128` depending on the precision of the constant: +Tapi bila sisi kanan berupa konstanta numerik, variabel baru bisa jadi `int`, `float64`, atau `complex128` bergantung kepada presisi dari konstanta: i := 42 // int f := 3.142 // float64 g := 0.867 + 0.5i // complex128 -Try changing the initial value of `v` in the example code and observe how its type is affected. +Coba ubah nilai awal dari `v` pada contoh kode dan perhatikan bagaimana tipenya berubah. .play basics/type-inference.go -* Constants +* Konstanta -Constants are declared like variables, but with the `const` keyword. +Konstanta dideklarasikan seperti variabel, tapi dengan kata `const`. -Constants can be character, string, boolean, or numeric values. +Konstanta bisa bernilai karakter, string, boolean, atau numerik. -Constants cannot be declared using the `:=` syntax. +Konstanta tidak bisa dideklarasikan dengan sintaks `:=`. .play basics/constants.go -* Numeric Constants +* Konstanta Numerik -Numeric constants are high-precision _values_. +Konstanta numerik adalah _nilai_ dengan presisi-tinggi. -An untyped constant takes the type needed by its context. +Konstanta yang tidak bertipe menggunakan tipe yang dibutuhkan sesuai dengan konteksnya. -Try printing `needInt(Big)` too. +Coba cetak juga `needInt(Big)`. (An `int` can store at maximum a 64-bit integer, and sometimes less.) .play basics/numeric-constants.go -* Congratulations! +* Selamat! -You finished this lesson! +Anda telah menyelesaikan pelajaran ini! -You can go back to the list of [[/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]]. +Anda bisa kembali ke daftar +[[/list][modul]] +untuk melihat apa yang bisa dipelajari selanjutnya, atau meneruskan dengan +[[javascript:click(".next-page")][pelajaran selanjutnya]]. diff --git a/content/concurrency.article b/content/concurrency.article index 35945b0..bc62a34 100644 --- a/content/concurrency.article +++ b/content/concurrency.article @@ -1,87 +1,103 @@ -Concurrency -Go provides concurrency constructions as part of the core language. This lesson presents them and gives some examples on how they can be used. +Konkurensi +Go menyediakan konstruksi konkurensi sebagai bagian dari inti bahasanya. Pelajaran kali ini menjelaskan dan memberikan beberapa contoh penggunaannya. -The Go Authors +Para Penggubah Go https://golang.org * Goroutines -A _goroutine_ is a lightweight thread managed by the Go runtime. +Sebuah _goroutine_ yaitu suatu thread ringan yang diatur oleh Go runtime. +Perintah go f(x, y, z) -starts a new goroutine running +memulai sebuah goroutine baru `f` dengan menjalankan f(x, y, z) -The evaluation of `f`, `x`, `y`, and `z` happens in the current goroutine and the execution of `f` happens in the new goroutine. +Evaluasi dari nilai `f`, `x`, `y`, dan `z` terjadi di goroutine yang memanggil dan eksekusi dari `f` terjadi di goroutine yang baru. -Goroutines run in the same address space, so access to shared memory must be synchronized. The [[https://golang.org/pkg/sync/][`sync`]] package provides useful primitives, although you won't need them much in Go as there are other primitives. (See the next slide.) +Goroutine berjalan di ruang alamat yang sama, sehingga akses ke +_shared_memory_ harus disinkronisasi. +Paket +[[https://golang.org/pkg/sync/][`sync`]] +menyediakan fungsi primitif untuk sinkronisasi, walaupun anda tidak terlalu +membutuhkannya karena ada fungsi primitif lainnya. +(Lihat slide selanjutnya.) .play concurrency/goroutines.go -* Channels +* Kanal -Channels are a typed conduit through which you can send and receive values with the channel operator, `<-`. +Kanal adalah sebuah penghubung tipe yang mana anda bisa mengirim dan menerima nilai dengan operator kanal, `<-`. - ch <- v // Send v to channel ch. - v := <-ch // Receive from ch, and - // assign value to v. + ch <- v // Kirim v ke kanal ch. + v := <-ch // Terima dari ch, dan simpan nilainya ke v. -(The data flows in the direction of the arrow.) +(Aliran data sesuai dengan arah panah.) -Like maps and slices, channels must be created before use: +Seperti map dan slice, kanal harus dibuat sebelum digunakan: ch := make(chan int) -By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables. +Secara bawaan, pengiriman dan penerimaan ditahan sampai sisi yang lain siap. +Hal ini membolehkan goroutine untuk melakukan sinkronisasi tanpa melakukan penguncian secara eksplisit atau menggunakan variabel kondisi. The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result. .play concurrency/channels.go -* Buffered Channels +* Kanal dengan buffer -Channels can be _buffered_. Provide the buffer length as the second argument to `make` to initialize a buffered channel: +Kanal memiliki _buffer_. +Cukup dengan menambahkan panjang buffer ke argumen kedua pada `make` untuk menginisialisasi buffer kanal: ch := make(chan int, 100) -Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty. +Pengiriman ke kanal buffer akan ditahan bila buffer telah penuh. +Penerimaan akan ditahan saat buffer kosong. -Modify the example to overfill the buffer and see what happens. +Ubahlah contoh untuk memenuhi buffer dan lihat apa yang terjadi. .play concurrency/buffered-channels.go -* Range and Close +* "range" dan "close" -A sender can `close` a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after +Pengirim dapat menutup (`close`) sebuah kanal untuk menandakan bahwa tidak ada lagi data yang dikirim. +Penerima dapat memeriksa apakah kanal telah ditutup dengan menambahkan parameter kedua pada ekspresi penerimaan: v, ok := <-ch -`ok` is `false` if there are no more values to receive and the channel is closed. +`ok` bernilai `false` jika tidak ada lagi nilai yang diterima dan kanal telah ditutup. -The loop `for`i`:=`range`c` receives values from the channel repeatedly until it is closed. +Pengulangan `for`i`:=`range`c` menerima nilai dari kanal berulang kali sampai ditutup. -*Note:* Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic. +*Catatan:* Hanya pengirim yang menutup kanal, penerima tidak pernah menutupnya. +Mengirim ke kanal yang telah tertutup akan menyebabkan kepanikan. -*Another*note:* Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a `range` loop. +*Catatan*lain:* Kanal tidak seperti file; yang mana anda tidak selalu perlu +menutupnya. +Penutupan hanya diperlukan saat penerima harus diberitahu bahwa tidak ada lagi +nilai yang akan diterima, misalnya untuk menghentikan pengulangan pada +`range`. .play concurrency/range-and-close.go -* Select +* Perintah "select" -The `select` statement lets a goroutine wait on multiple communication operations. +Perintah `select` membuat goroutine menunggu operasi komunikasi. -A `select` blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready. +`select` menahan pembacaan sampai salah satu kondisinya dapat berjalan, kemudian ia mengeksekusi kondisi tersebut. +Ia memilih salah satu kondisi secara acak jika banyak kondisi telah siap. .play concurrency/select.go -* Default Selection +* Seleksi bawaan -The `default` case in a `select` is run if no other case is ready. +Kondisi `default` pada `select` dijalankan jika tidak ada kondisi yang siap. -Use a `default` case to try a send or receive without blocking: +Gunakan kondisi `default` untuk mencoba mengirim dan menerima tanpa diblok: select { case i := <-c: @@ -92,15 +108,19 @@ Use a `default` case to try a send or receive without blocking: .play concurrency/default-selection.go -* Exercise: Equivalent Binary Trees +* Latihan: Binary Tree yang sama -There can be many different binary trees with the same sequence of values stored in it. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13. +Ada banyak cara membangun sebuah _binary_tree_ dengan urutan nilai yang sama +tersimpan di _leave_ nya. +Sebagai contohnya, berikut dua binary tree yang menyimpan urutan 1, 1, 2, 3, +5, 8, 13. .image /content/img/tree.png -A function to check whether two binary trees store the same sequence is quite complex in most languages. We'll use Go's concurrency and channels to write a simple solution. +Sebuah fungsi yang memeriksa apakah dua binary tree menyimpan urutan yang sama, akan cukup kompleks bila diiimplementasikan pada kebanyakan bahasa pemrograman. +Kita akan gunakan konkurensi dan kanal untuk menulis sebuah solusi sederhana menggunakan Go. -This example uses the `tree` package, which defines the type: +Contoh ini menggunakan paket `tree`, yang mendefinisikan tipe: type Tree struct { Left *Tree @@ -109,27 +129,29 @@ This example uses the `tree` package, which defines the type: } -Continue description on [[javascript:click('.next-page')][next page]]. +Lanjutkan deskripsi pada [[javascript:click(".next-page")][halaman selanjutnya]]. -* Exercise: Equivalent Binary Trees +* Latihan: Binary Tree yang sama -*1.* Implement the `Walk` function. +*1.* Implementasikan fungsi `Walk`. -*2.* Test the `Walk` function. +*2.* Uji fungsi `Walk`. -The function `tree.New(k)` constructs a randomly-structured (but always sorted) binary tree holding the values `k`, `2k`, `3k`, ..., `10k`. +Fungsi `tree.New(k)` membuat binary tree yang secara acak-terstuktur (tetapi +selalu terurut) yang menyimpan nilai `k`, `2k`, `3k`, ..., `10k`. -Create a new channel `ch` and kick off the walker: +Buat sebuah kanal baru `ch` dan jalankan fungsi `Walk` go Walk(tree.New(1), ch) -Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10. +Kemudian baca dan cetak 10 nilai dari kanal. +Ia harusnya mengeluarkan angka 1, 2, 3, ..., 10. -*3.* Implement the `Same` function using `Walk` to determine whether `t1` and `t2` store the same values. +*3.* Implementasikan fungsi `Same` menggunakan `Walk` untuk menentukan apakah `t1` dan `t2` menyimpan nilai yang sama. -*4.* Test the `Same` function. +*4.* Uji fungsi `Same`. -`Same(tree.New(1),`tree.New(1))` should return true, and `Same(tree.New(1),`tree.New(2))` should return false. +`Same(tree.New(1),`tree.New(1))` mengembalikan nilai `true`, dan `Same(tree.New(1),`tree.New(2))` mengembalikan nilai `false`. The documentation for `Tree` can be found [[https://godoc.org/golang.org/x/tour/tree#Tree][here]]. @@ -137,72 +159,86 @@ The documentation for `Tree` can be found [[https://godoc.org/golang.org/x/tour/ * sync.Mutex -We've seen how channels are great for communication among goroutines. +Kita telah melihat bagaimana _channel_ sangat bagus untuk komunikasi antara +beberapa _goroutine_. -But what if we don't need communication? What if we just want to make sure only -one goroutine can access a variable at a time to avoid conflicts? +Namun bagaimana jika kita tidak ingin komunikasi? +Bagaimana jika kita hanya ingin memastikan hanya satu goroutine yang dapat +mengakses suatu variabel pada satu waktu untuk menghindari konflik? -This concept is called _mutual_exclusion_, and the conventional name for the data structure that provides it is _mutex_. +Konsep ini disebut juga dengan _mutual_exclusion_, dan nama umum untuk +struktur data yang menyediakan fungsi tersebut adalah _mutex_. -Go's standard library provides mutual exclusion with -[[https://golang.org/pkg/sync/#Mutex][`sync.Mutex`]] and its two methods: +Pustaka standar Go menyediakan mutual exclusion dengan +[[https://golang.org/pkg/sync/#Mutex][`sync.Mutex`]] +dan dua fungsinya: - `Lock` - `Unlock` -We can define a block of code to be executed in mutual exclusion by surrounding it -with a call to `Lock` and `Unlock` as shown on the `Inc` method. +Kita bisa mendefinisikan sebuah blok kode untuk dieksekusi secara +_mutual_exclusion_ dengan mengungkungnya dengan pemanggilan fungsi `Lock` dan +`Unlock` seperti yang terlihat pada method `Inc`. -We can also use `defer` to ensure the mutex will be unlocked as in the `Value` method. +Kita juga bisa menggunakan `defer` untuk memastikan mutex akan dibuka kembali +seperti pada method `Value`. -.play concurrency/mutex-counter.go +* Latihan: Web Crawler -* Exercise: Web Crawler +Dalam latihan ini anda akan menggunakan fitur konkurensi Go untuk +mem-paralelkan sebuah _web_crawler_. -In this exercise you'll use Go's concurrency features to parallelize a web crawler. +Ubah fungsi `Crawl` untuk mengambil URL secara paralel tanpa ada duplikasi +(mengambil URL yang sama dua kali). -Modify the `Crawl` function to fetch URLs in parallel without fetching the same URL twice. - -_Hint_: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not -safe for concurrent use! +_Petunjuk_: anda bisa menyimpan _cache_ dari URL yang telah diambil +menggunakan sebuah map, tapi map tidak aman untuk digunakan secara konkuren! .play concurrency/exercise-web-crawler.go -* Where to Go from here... +* Kemana selanjutnya ... -#appengine: You can get started by -#appengine: [[https://golang.org/dl/][installing Go]]. +#appengine: Anda dapat memulai dengan +#appengine: [[https://golang.org/doc/install/][memasang Go]]. -#appengine: Once you have Go installed, the -The -[[https://golang.org/doc/][Go Documentation]] is a great place to -#appengine: continue. -start. -It contains references, tutorials, videos, and more. +#appengine: Saat anda telah memasang Go, +[[https://golang.org/doc/][Dokumentasi Go]] +adalah tempat yang bagus untuk +#appengine: melanjutkan. +memulai. +Dokumentasi tersebut berisi referensi, tutorial, video, dan banyak lagi. -To learn how to organize and work with Go code, watch [[https://www.youtube.com/watch?v=XCsL89YtqCs][this screencast]] or read [[https://golang.org/doc/code.html][How to Write Go Code]]. +Untuk belajar cara mengorganisir dan bekerja dengan kode Go, lihat +[[https://www.youtube.com/watch?v=XCsL89YtqCs][siaran berikut]] +atau baca +[[https://golang.org/doc/code.html][Cara Menulis Kode Go]]. -If you need help with the standard library, see the [[https://golang.org/pkg/][package reference]]. For help with the language itself, you might be surprised to find the [[https://golang.org/ref/spec][Language Spec]] is quite readable. +Jika anda membutuhkan bantuan dengan pustaka Go, lihat +[[https://golang.org/pkg/][referensi paket]]. +Untuk bantuan mengenai bahasa itu sendiri, anda mungkin bisa melihat +[[https://golang.org/ref/spec][Spesifikasi Bahasa]] +cukup dapat bisa dibaca. -To further explore Go's concurrency model, watch -[[https://www.youtube.com/watch?v=f6kdp27TYZs][Go Concurrency Patterns]] -([[https://talks.golang.org/2012/concurrency.slide][slides]]) -and -[[https://www.youtube.com/watch?v=QDDwwePbDtw][Advanced Go Concurrency Patterns]] +Untuk mengeksplorasi lebih lanjut tentang model konkurensi dari Go, tontonlah +[[https://www.youtube.com/watch?v=f6kdp27TYZs][Pola Konkurensi]] +([[https://talks.golang.org/2012/concurrency.slide][slide]]) +dan +[[https://www.youtube.com/watch?v=QDDwwePbDtw][Pola Konkurensi Go Lanjutan]] ([[https://talks.golang.org/2013/advconc.slide][slides]]) -and read the -[[https://golang.org/doc/codewalk/sharemem/][Share Memory by Communicating]] -codewalk. +dan baca +[[https://golang.org/doc/codewalk/sharemem/][Berbagi Memory dengan Komunikasi]]. -To get started writing web applications, watch +Untuk memulai membuat aplikasi web, tontonlah [[https://vimeo.com/53221558][A simple programming environment]] ([[https://talks.golang.org/2012/simple.slide][slides]]) -and read the -[[https://golang.org/doc/articles/wiki/][Writing Web Applications]] tutorial. - -The [[https://golang.org/doc/codewalk/functions/][First Class Functions in Go]] codewalk gives an interesting perspective on Go's function types. +dan baca tutorial +[[https://golang.org/doc/articles/wiki/][Menulis Aplikasi Web]]. -The [[https://blog.golang.org/][Go Blog]] has a large archive of informative Go articles. +Artikel +[[https://golang.org/doc/codewalk/functions/][First Class Functions in Go]] +memberikan perspektif menarik tentang tipe fungsi pada Go. -Visit [[https://golang.org][golang.org]] for more. +[[https://blog.golang.org/][Blognya Go]] +memiliki sejumlah arsip artikel informatif tentang Go. +Kunjungi [[https://golang.org][golang.org]] untuk lebih lanjut. diff --git a/content/flowcontrol.article b/content/flowcontrol.article index 0f25ab4..68a5963 100644 --- a/content/flowcontrol.article +++ b/content/flowcontrol.article @@ -1,178 +1,196 @@ -Flow control statements: for, if, else, switch and defer -Learn how to control the flow of your code with conditionals, loops, switches and defers. +Perintah kontrol alur: for, if, else, switch, dan defer +Belajar cara mengontrol alur kode dengan kondisional, pengulangan, `switch` dan `defer`. -The Go Authors +Para Penggubah Go https://golang.org -* For +* Pengulangan ("for") -Go has only one looping construct, the `for` loop. +Go hanya memiliki satu konstruk pengulangan, yaitu `for`. -The basic `for` loop has three components separated by semicolons: +Dasar dari pengulangan `for` yaitu memiliki tiga komponen yang dipisahkan oleh +titik-koma: -- the init statement: executed before the first iteration -- the condition expression: evaluated before every iteration -- the post statement: executed at the end of every iteration +- perintah awal: dieksekusi sebelum iterasi pertama +- ekspresi kondisi: dievaluasi sebelum iterasi pertama +- perintah akhir: dieksekusi disetiap akhir iterasi -The init statement will often be a short variable declaration, and the -variables declared there are visible only in the scope of the `for` -statement. +Perintah awal biasanya berupa deklarasi variabel singkat, dan variabel yang +dideklarasikan tersebut hanya dapat digunakan dalam skop perintah `for`. -The loop will stop iterating once the boolean condition evaluates to `false`. +Pengulangan akan berhenti saat ekspresi kondisi bernilai `false`. -*Note:* Unlike other languages like C, Java, or JavaScript there are no parentheses -surrounding the three components of the `for` statement and the braces `{`}` are -always required. +*Catatan:* Tidak seperti bahasa C, Java, atau JavaScript, tidak ada tanda +kurung yang digunakan menutupi ketiga komponen dari perintah `for` dan tanda +kurung kurawal `{`}` selalu dibutuhkan.. .play flowcontrol/for.go -* For continued +* Pengulangan lanjutan -The init and post statements are optional. +Perintah awal dan akhir adalah opsional. .play flowcontrol/for-continued.go -* For is Go's "while" +* For adalah Go-nya "while" -At that point you can drop the semicolons: C's `while` is spelled `for` in Go. +Dengan cara ini anda bisa menghilangkan titik-koma: `while` nya C dieja dengan `for` pada Go. .play flowcontrol/for-is-gos-while.go -* Forever +* Pengulangan selamanya -If you omit the loop condition it loops forever, so an infinite loop is compactly expressed. +Jika anda mengosongkan kondisi maka pengulangan akan berjalan selamanya, dengan ini pengulangan tanpa henti dapat diekspresikan dengan singkat. .play flowcontrol/forever.go -* If +* Kondisi ("if") -Go's `if` statements are like its `for` loops; the expression need not be -surrounded by parentheses `(`)` but the braces `{`}` are required. +Perintah `if` mirip seperti pada pengulangan `for`; ekspresinya tidak harus +ditutupi dengan tanda-kurung `(`)` namun tanda `{`}` diharuskan. .play flowcontrol/if.go -* If with a short statement +* Kondisi "if" singkat -Like `for`, the `if` statement can start with a short statement to execute before the condition. +Seperti pada `for`, perintah `if` bisa diawali dengan perintah singkat untuk dieksekusi sebelum kondisi. -Variables declared by the statement are only in scope until the end of the `if`. +Variabel yang dideklarasikan pada perintah singkat tersebut hanya berlaku sampai lingkup sampai kondisi `if` berakhir. -(Try using `v` in the last `return` statement.) +(Coba gunakan `v` di akhir perintah `return`.) .play flowcontrol/if-with-a-short-statement.go -* If and else +* Kondisi "if" dan "else" -Variables declared inside an `if` short statement are also available inside any -of the `else` blocks. +Variabel yang dideklarasikan dalam perintah singkat `if` juga dapat digunakan +dalam blok `else`. -(Both calls to `pow` return their results before the call to `fmt.Println` -in `main` begins.) +(Kedua pemanggilan ke `pow` dieksekusi dan dikembalikan sebelum pemanggilan ke + `fmt.Println` di `main` dimulai.) .play flowcontrol/if-and-else.go -* Exercise: Loops and Functions +* Latihan: Pengulangan dan Fungsi -As a way to play with functions and loops, let's implement a square root function: given a number x, we want to find the number z for which z² is most nearly x. +Cara sederhana untuk bermain dengan pengulangan dan fungsi yaitu dengan +mengimplementasikan fungsi kuadrat: diberikan sebuah input bilangan x, kita +akan cari bilangan z yang mana z² paling mendekati ke x. -Computers typically compute the square root of x using a loop. -Starting with some guess z, we can adjust z based on how close z² is to x, -producing a better guess: +Komputer biasanya menghitung akar kuadrat dari x menggunakan sebuah +pengulangan. +Dimulai dari nilai z, kita dapat mengatur z berdasarkan berapa dekat z² +terhadap x, menghasilkan terkaan yang lebih mendekati: - z -= (z*z - x) / (2*z) + z -= (z * z - x) / (2*z) -Repeating this adjustment makes the guess better and better -until we reach an answer that is as close to the actual square root as can be. +Dengan mengulangi persamaan di atas akan membuat pencarian kita semakin +mendekati nilai kuadrat yang sebenarnya. -Implement this in the `func`Sqrt` provided. -A decent starting guess for z is 1, no matter what the input. -To begin with, repeat the calculation 10 times and print each z along the way. -See how close you get to the answer for various values of x (1, 2, 3, ...) -and how quickly the guess improves. +Implementasikan persamaan tersebut dalam `func`Sqrt` yang telah disediakan. +Nilai awal yang aman untuk z adalah 1, berapapun inputnya. +Sebagai permulaan, ulangi perhitungan 10 kali dan cetak nilai z. +Lihat seberapa dekat hasil perhitungan anda dengan jawaban dari beragam nilai +x (1, 2, 3, ...) dan seberapa cepat tebakan anda diperbaiki. -Hint: To declare and initialize a floating point value, -give it floating point syntax or use a conversion: +Petunjuk: untuk mendeklarasikan dan menginisialisasi nilai floating point, +gunakan sintaks floating point atau konversi: z := 1.0 z := float64(1) -Next, change the loop condition to stop once the value has stopped -changing (or only changes by a very small amount). -See if that's more or fewer than 10 iterations. -Try other initial guesses for z, like x, or x/2. -How close are your function's results to the [[https://golang.org/pkg/math/#Sqrt][math.Sqrt]] in the standard library? +Selanjutnya, ubah kondisi pengulangan untuk berhenti saat nilainya sudah tidak +berubah lagi (atau hanya berubah dengan delta yang sangat kecil). +Lihat apakah iterasinya lebih sedikit atau lebih banyak dari 10 iterasi. +Coba nilai terkaan awal untuk z, misalnya x, atau x/2. +Seberapa dekat hasil anda dengan nilai +[[https://golang.org/pkg/math/#Sqrt][math.Sqrt]] +dari pustaka standar? -(*Note:* If you are interested in the details of the algorithm, the z² − x above -is how far away z² is from where it needs to be (x), and the division by 2z is the derivative -of z², to scale how much we adjust z by how quickly z² is changing. -This general approach is called [[https://en.wikipedia.org/wiki/Newton%27s_method][Newton's method]]. -It works well for many functions but especially well for square root.) +(*Catatan:* Jika anda tertarik dengan rincian dari algoritma, persamaan z² − x +adalah seberapa jauh nilai z² dari yang diinginkan (x), dan pembagian dengan +(2*z) adalah turunan dari z², untuk melihat berapa banyak kita harus +memperbaiki nilai z dengan melihat berapa cepat z² berubah. +Pendekatan ini disebut dengan +[[https://en.wikipedia.org/wiki/Newton%27s_method][metode Newton]]. +Ia bekerja dengan baik untuk beragam fungsi, +terutama kuadrat. .play flowcontrol/exercise-loops-and-functions.go -* Switch +* Perintah "switch" -A `switch` statement is a shorter way to write a sequence of `if`-`else` statements. -It runs the first case whose value is equal to the condition expression. +Perintah switch untuk mempermudah membuat beberapa perintah kondisi +`if`-`else`. +Go akan menjalankan case pertama yang nilainya sama dengan ekspresi kondisi +yang diberikan. -Go's switch is like the one in C, C++, Java, JavaScript, and PHP, -except that Go only runs the selected case, not all the cases that follow. -In effect, the `break` statement that is needed at the end of each case in those -languages is provided automatically in Go. -Another important difference is that Go's switch cases need not -be constants, and the values involved need not be integers. +Perintah switch pada Go hampir sama dengan bahasa C, C++, Java, Javascript, +dan PHP; +hanya saja pada Go akan menjalankan case yang terpilih, bukan semua case yang +ada selanjutnya. +Efeknya, perintah `break` yang biasanya dibutuhkan diakhir setiap case pada +bahasa lainnya dibuat secara otomatis oleh Go. +Perbedaan penting lainnya yaitu ekspresi kondisi case pada Go tidak harus +konstanta, dan nilainya tidak harus integer. .play flowcontrol/switch.go -* Switch evaluation order +* Urutan evaluasi "switch" -Switch cases evaluate cases from top to bottom, stopping when a case succeeds. +Kondisi pada `switch` dievaluasi dari atas ke bawah, berhenti saat sebuah +kondisi sukses. -(For example, +Sebagai contoh, switch i { case 0: case f(): } -does not call `f` if `i==0`.) +tidak akan memanggil fungsi `f` jika `i==0`. -#appengine: *Note:* Time in the Go playground always appears to start at -#appengine: 2009-11-10 23:00:00 UTC, a value whose significance is left as an -#appengine: exercise for the reader. +#appengine: *Catatan:* waktu dalam Go playground selalu berawal dari +#appengine: 2009-11-10 23:00:00 UTC, sebuah nilai yang makna bisa dicari oleh +#appengine: pembaca. .play flowcontrol/switch-evaluation-order.go -* Switch with no condition +* Perintah "switch" tanpa kondisi -Switch without a condition is the same as `switch`true`. +Perintah `switch` tanpa sebuah kondisi sama seperti `switch`true`. -This construct can be a clean way to write long if-then-else chains. +Konstruksi ini merupakan cara yang bersih untuk menulis rantaian if-then-else +yang panjang. .play flowcontrol/switch-with-no-condition.go -* Defer +* Perintah "defer" -A defer statement defers the execution of a function until the surrounding -function returns. +Perintah `defer` menunda eksekusi dari sebuah fungsi sampai fungsi yang +melingkupinya selesai. -The deferred call's arguments are evaluated immediately, but the function call -is not executed until the surrounding function returns. +Argumen untuk pemanggilan `defer` dievaluasi langsung, tapi pemanggilan fungsi +tidak dieksekusi sampai fungsi yang melingkupinya selesai. .play flowcontrol/defer.go -* Stacking defers +* Penundaan bertumpuk -Deferred function calls are pushed onto a stack. When a function returns, its -deferred calls are executed in last-in-first-out order. +Fungsi yang dipanggil dengan `defer` di- _push_ ke sebuah _stack_. +Saat fungsi berakhir, panggilan yang tadi ditunda dieksekusi dengan urutan +last-in-first-out (yang terakhir masuk menjadi pertama keluar). -To learn more about defer statements read this -[[https://blog.golang.org/defer-panic-and-recover][blog post]]. +Untuk belajar lebih lanjut tentang perintah `defer` bacalah +[[https://blog.golang.org/defer-panic-and-recover][blog berikut]]. .play flowcontrol/defer-multi.go -* Congratulations! +* Selamat! -You finished this lesson! +Anda telah menyelesaikan pelajaran ini! -You can go back to the list of [[/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]]. +Anda bisa kembali ke daftar +[[/list][modul]] +untuk melihat apa yang bisa dipelajari selanjutnya, atau meneruskan ke +[[javascript:click(".next-page")][pelajaran selanjutnya]]. diff --git a/content/methods.article b/content/methods.article index 34aa673..625ba65 100644 --- a/content/methods.article +++ b/content/methods.article @@ -1,250 +1,267 @@ -Methods and interfaces -This lesson covers methods and interfaces, the constructs that define objects and their behavior. +Method dan Interface +Pelajaran ini membahas method dan interface, konstruksi yang membuat objek dan perilakunya. -The Go Authors +Para Penggubah Go https://golang.org -* Methods +* Method -Go does not have classes. -However, you can define methods on types. +Go tidak memiliki class. +Namun, anda bisa mendefinisikan method pada tipe. -A method is a function with a special _receiver_ argument. +Sebuah method adalah sebuah fungsi dengan argumen khusus _receiver_. -The receiver appears in its own argument list between the `func` keyword and -the method name. +_receiver_ muncul pada bagian antara kata kunci `func` and nama method. -In this example, the `Abs` method has a receiver of type `Vertex` named `v`. +Pada contoh berikut, method `Abs` memiliki _receiver_ dengan tipe `Vertex` +bernama `v`. .play methods/methods.go -* Methods are functions +* Method adalah fungsi -Remember: a method is just a function with a receiver argument. +Ingat: sebuah method hanyalah fungsi dengan argumen sebuah _receiver_. -Here's `Abs` written as a regular function with no change in functionality. +Berikut ini `Abs` ditulis sebagai fungsi biasa tanpa ada perubahan pada +fungsionalitas. .play methods/methods-funcs.go -* Methods continued +* Method lanjutan -You can declare a method on non-struct types, too. +Anda bisa mendeklarasikan method pada tipe selain struct just. -In this example we see a numeric type `MyFloat` with an `Abs` method. +Pada contoh berikut kita dapat melihat sebuah tipe numerik `MyFloat` dengan +method `Abs`. -You can only declare a method with a receiver whose type is defined in the same -package as the method. -You cannot declare a method with a receiver whose type is defined in another -package (which includes the built-in types such as `int`). +Anda hanya bisa mendeklerasikan sebuah method dengan sebuah receiver yang +tipenya didefinisikan di paket yang sama dengan method-nya. +Anda tidak bisa mendeklarasikan sebuah method dengan receiver yang tipenya +didefinisikan dipaket yang lain (termasuk tipe dasar seperti `int`). .play methods/methods-continued.go -* Pointer receivers +* Method dengan pointer-receiver -You can declare methods with pointer receivers. +Anda bisa mendeklarasikan method dengan _receiver_ berupa pointer. -This means the receiver type has the literal syntax `*T` for some type `T`. -(Also, `T` cannot itself be a pointer such as `*int`.) +Hal ini berarti tipe _receiver_ memiliki sintaks `*T` untuk tipe `T`. +(Dan juga, `T` itu sendiri tidak bisa berupa pointer ke tipe dasar seperti + `*int`.) -For example, the `Scale` method here is defined on `*Vertex`. +Sebagai contohnya, method `Scale` didefinisikan pada `*Vertex`. -Methods with pointer receivers can modify the value to which the receiver -points (as `Scale` does here). -Since methods often need to modify their receiver, pointer receivers are more -common than value receivers. +Method dengan pointer-receiver dapat mengubah nilai yang diacu oleh receiver +(tidak seperti `Scale`). +Karena method seringkali perlu mengubah receiver-nya, pointer-receiver lebih +umum ditemukan daripada receiver yang bukan pointer. -Try removing the `*` from the declaration of the `Scale` function on line 16 -and observe how the program's behavior changes. +Coba hapus `*` dari deklarasi fungsi `Scale` pada baris 16 dan perhatikan +bagaimana perilaku program berubah. -With a value receiver, the `Scale` method operates on a copy of the original -`Vertex` value. -(This is the same behavior as for any other function argument.) -The `Scale` method must have a pointer receiver to change the `Vertex` value -declared in the `main` function. +Dengan receiver-sebagai-value, method `Scale` beroperasi pada salinan dari +nilai asli `Vertex`. +(Perilaku ini juga berlaku pada argumen pada fungsi.) +Method `Scale` harus memiliki sebuah pointer-receiver untuk dapat mengubah +nilai `Vertex` yang dideklarasikan pada fungsi `main`. .play methods/methods-pointers.go -* Pointers and functions +* Pointers dan fungsi -Here we see the `Abs` and `Scale` methods rewritten as functions. +Di sini kita lihat method `Abs` dan `Scale` dibuat ulang sebagai fungsi. -Again, try removing the `*` from line 16. -Can you see why the behavior changes? -What else did you need to change for the example to compile? +Sekali lagi, coba hilangkan `*` pada baris 16. +Bisakah anda melihat perubahan perilakunya? +Apa yang harus anda ubah selanjutnya supaya contoh tersebut dapat di +_compile_? -(If you're not sure, continue to the next page.) +(Jika anda tidak yakin, lanjutkan ke tahap berikutnya.) .play methods/methods-pointers-explained.go -* Methods and pointer indirection +* Method dan pointer tidak langsung -Comparing the previous two programs, you might notice that -functions with a pointer argument must take a pointer: +Bandingkan dua program sebelumnya, anda mungkin memperhatikan bahwa fungsi +dengan sebuah argumen pointer harus menerima sebuah pointer: - var v Vertex + var V Vertex ScaleFunc(v, 5) // Compile error! ScaleFunc(&v, 5) // OK -while methods with pointer receivers take either a value or a pointer as the -receiver when they are called: +Sementara method dengan pointer-receiver dapat menerima sebuah nilai atau +sebuah pointer sebagai receiver saat dipanggil: var v Vertex - v.Scale(5) // OK + v.Scale(5) // OK p := &v - p.Scale(10) // OK + p.Scale(10) // OK -For the statement `v.Scale(5)`, even though `v` is a value and not a pointer, -the method with the pointer receiver is called automatically. -That is, as a convenience, Go interprets the statement `v.Scale(5)` as -`(&v).Scale(5)` since the `Scale` method has a pointer receiver. +Untuk perintah `v.Scale(5)`, walaupun `v` adalah sebuah nilai bukan sebuah +pointer, method dengan pointer-receiver akan dipanggil secara otomatis. +Maka, untuk mempermudah, Go menginterpretasikan perintah `v.Scale(5)` sebagai +`(&v).Scale(5)` karena method Scale memiliki pointer-receiver. .play methods/indirection.go -* Methods and pointer indirection (2) +* Method dan pointer tidak langsung (2) -The equivalent thing happens in the reverse direction. +Hal yang sama berlaku sebaliknya. -Functions that take a value argument must take a value of that specific type: +Fungsi yang menerima argumen nilai harus mendapatkan sebuah nilai dari tipe +yang spesifik: var v Vertex fmt.Println(AbsFunc(v)) // OK fmt.Println(AbsFunc(&v)) // Compile error! -while methods with value receivers take either a value or a pointer as the -receiver when they are called: +Sementara method dengan value-receiver bisa menerima sebuah nilai atau sebuah +pointer sebagai receiver saat dipanggil: var v Vertex fmt.Println(v.Abs()) // OK p := &v fmt.Println(p.Abs()) // OK -In this case, the method call `p.Abs()` is interpreted as `(*p).Abs()`. +Pada kasus ini, pemanggilan method `p.Abs()` diinterpretasikan sebagai +`(*p).Abs()`. .play methods/indirection-values.go -* Choosing a value or pointer receiver +* Memilih receiver nilai atau pointer -There are two reasons to use a pointer receiver. +Ada dua alasan kenapa menggunakan _pointer-receiver_. -The first is so that the method can modify the value that its receiver points to. +Pertama adalah supaya method dapat mengubah nilai yang ditunjuk oleh receiver. -The second is to avoid copying the value on each method call. -This can be more efficient if the receiver is a large struct, for example. +Kedua adalah untuk menghindari menyalin nilai setiap kali method dipanggil. +Hal ini bisa lebih efisien jika receiver adalah sebuah struct yang besar, +sebagai contohnya. -In this example, both `Scale` and `Abs` are with receiver type `*Vertex`, -even though the `Abs` method needn't modify its receiver. +Pada contoh ini, `Scale` dan `Abs` memiliki tipe receiver `*Vertex`, walaupun +method `Abs` tidak perlu mengubah receiver-nya. -In general, all methods on a given type should have either value or pointer -receivers, but not a mixture of both. -(We'll see why over the next few pages.) +Secara umum, semua method dari sebuah tipe harus memiliki receiver sebagai +nilai atau sebagai pointer, tapi tidak gabungan dari keduanya. +(Kita akan lihat alasannya pada beberapa laman berikutnya.) .play methods/methods-with-pointer-receivers.go -* Interfaces +* Interface -An _interface_type_ is defined as a set of method signatures. +Sebuah _type_interface_ didefinisikan sebagai sebuah kumpulan method penanda. -A value of interface type can hold any value that implements those methods. +Nilai dari tipe interface dapat menyimpan nilai apapun yang mengimplementasikan method tersebut. -*Note:* There is an error in the example code on line 22. -`Vertex` (the value type) doesn't implement `Abser` because -the `Abs` method is defined only on `*Vertex` (the pointer type). +*Catatan:* Terdapat kesalahan di contoh kode pada baris 22. +`Vertex` (tipe nilai) tidak memenuhi `Abser` karena method `Abs` hanya +didefinisikan pada `*Vertex` (tipe pointer). .play methods/interfaces.go -* Interfaces are implemented implicitly +* Interface dipenuhi secara implisit -A type implements an interface by implementing its methods. -There is no explicit declaration of intent, no "implements" keyword. +Sebuah tipe mengimplementasikan sebuah interface dengan mengimplementasikan +method-methodnya. +Tidak ada deklarasi eksplisit; tidak ada perintah "implements". -Implicit interfaces decouple the definition of an interface from its -implementation, which could then appear in any package without prearrangement. +Interface implisit memisahkan definisi dari sebuah interface dari +implementasinya, yang bisa saja muncul dalam paket manapun tanpa adanya +penataan sebelumnya. .play methods/interfaces-are-satisfied-implicitly.go -* Interface values +* Nilai interface -Under the hood, interface values can be thought of as a tuple of a value and a -concrete type: +Isi interface dapat dibayangkan sebagai sebuah pasangan nilai dan sebuah tipe: - (value, type) + (nilai, tipe) -An interface value holds a value of a specific underlying concrete type. +Sebuah interface mengandung sebuah nilai dari tipe tertentu. -Calling a method on an interface value executes the method of the same name on -its underlying type. +Memanggil suatu method terhadap suatu interface akan mengeksekusi method +dengan nama yang sama pada tipe yang dipegangnya. .play methods/interface-values.go -* Interface values with nil underlying values +* Interface dengan nilai nil -If the concrete value inside the interface itself is nil, -the method will be called with a nil receiver. +Jika nilai sebenarnya dari interface itu sendiri adalah nil, method akan +dipanggil dengan receiver bernilai nil. -In some languages this would trigger a null pointer exception, -but in Go it is common to write methods that gracefully handle being called -with a nil receiver (as with the method `M` in this example.) +Pada beberapa bahasa pemrograman hal ini akan mengakibatkan null pointer +exception atau kesalahan karena pointer bernilai kosong, tapi pada Go sangat +umum menulis method dengan receiver bernilai nil (seperti method `M` pada +contoh di sebelah.) -Note that an interface value that holds a nil concrete value is itself non-nil. +Ingatlah bahwa sebuah isi interface yang mengandung nilai konkrit nil +sebenarnya adalah non-nil. .play methods/interface-values-with-nil.go -* Nil interface values +* Isi interface dengan nil -A nil interface value holds neither value nor concrete type. +Sebuah isi interface yang nil tidak mengandung nilai dan tipe konkrit. -Calling a method on a nil interface is a run-time error because there is no -type inside the interface tuple to indicate which _concrete_ method to call. +Memanggil sebuah method pada sebuah interface yang nil akan mengakibatkan +kesalahan run-time karena tidak ada tipe di dalam interface yang +mengindikasikan method _konkrit_ yang akan dipanggil. .play methods/nil-interface-values.go -* The empty interface +* Interface kosong -The interface type that specifies zero methods is known as the _empty_interface_: +Tipe interface yang tidak memiliki method dikenal juga dengan interface +kosong: interface{} -An empty interface may hold values of any type. -(Every type implements at least zero methods.) +Sebuah interface kosong bisa menyimpan nilai dari tipe apapun. +(Setiap tipe mengimplementasikan paling tidak nol method.) -Empty interfaces are used by code that handles values of unknown type. -For example, `fmt.Print` takes any number of arguments of type `interface{}`. +Interface kosong digunakan pada kode yang menangani nilai yang tidak +diketahui. +Sebagai contohnya, `fmt.Print` mengambil sejumlah argumen dengan tipe +`interface{}`. .play methods/empty-interface.go -* Type assertions +* Penegasan tipe -A _type_assertion_ provides access to an interface value's underlying concrete value. +Suatu _penegasan_tipe_ menyediakan akses ke isi interface di balik nilai +konkritnya. t := i.(T) -This statement asserts that the interface value `i` holds the concrete type `T` -and assigns the underlying `T` value to the variable `t`. +Perintah di atas menegaskan bahwa isi interface `i` menyimpan tipe konkrit `T` +dan memberikan nilai `T` ke variabel `t`. -If `i` does not hold a `T`, the statement will trigger a panic. +Jika `i tidak mengandung tipe `T`, perintah tersebut akan memicu `panic`. -To _test_ whether an interface value holds a specific type, -a type assertion can return two values: the underlying value -and a boolean value that reports whether the assertion succeeded. +Untuk _memeriksa_ apakah sebuah isi interface benar mengandung tipe tertentu, +penegasan tipe bisa mengembalikan dua nilai: nilai yang dikandung dan sebuah +nilai boolean yang memberitahu apakah penegasan sukses atau tidak. t, ok := i.(T) -If `i` holds a `T`, then `t` will be the underlying value and `ok` will be true. +Jika `i` mengandung `T`, maka `t` akan menyimpan nilai dan `ok` akan bernilai +true. -If not, `ok` will be false and `t` will be the zero value of type `T`, -and no panic occurs. +Jika tidak, `ok` akan bernilai false dan `t` akan bernilai kosong sesuai +dengan tipe `T`, dan panic tidak akan terjadi. -Note the similarity between this syntax and that of reading from a map. +Ingatlah kesamaan antara sintaks ini dengan membaca dari sebuah map. .play methods/type-assertions.go -* Type switches +* Penggunaan switch untuk tipe -A _type_switch_ is a construct that permits several type assertions in series. +Sebuah _tipe_switch_ adalah bentukan yang membolehkan beberapa penegasan tipe +secara serial. -A type switch is like a regular switch statement, but the cases in a type -switch specify types (not values), and those values are compared against -the type of the value held by the given interface value. +Tipe switch sama seperti perintah switch biasa, tapi dengan nilai case mengacu +pada tipe (bukan nilai), dan nilai case tersebut dibandingkan dengan tipe yang +dikandung oleh isi interface yang diberikan. switch v := i.(type) { case T: @@ -255,55 +272,57 @@ the type of the value held by the given interface value. // no match; here v has the same type as i } -The declaration in a type switch has the same syntax as a type assertion `i.(T)`, -but the specific type `T` is replaced with the keyword `type`. +Deklarasi dalam sebuah tipe switch memiliki sintaks yang sama dengan penegasan +tipe `i.(T)`, tapi dengan `T` diganti dengan kata `type`. -This switch statement tests whether the interface value `i` -holds a value of type `T` or `S`. -In each of the `T` and `S` cases, the variable `v` will be of type -`T` or `S` respectively and hold the value held by `i`. -In the default case (where there is no match), the variable `v` is -of the same interface type and value as `i`. +Perintah switch berikut menguji apakah isi interface `i` mengandung sebuah +nilai dari tipe `T` atau `S`. +Pada setiap `case` dari `T` dan `S`, variabel `v` akan memiliki tipe `T` atau +`S` dan memiliki nilai yang dikandung oleh `i`. +Pada `default case` (yang mana tidak ada tipe yang sama ditemukan), variabel +`v` akan memiliki tipe dan nilai yang sama dengan `i`. .play methods/type-switches.go -* Stringers +* Stringer -One of the most ubiquitous interfaces is [[//golang.org/pkg/fmt/#Stringer][`Stringer`]] defined by the [[//golang.org/pkg/fmt/][`fmt`]] package. +Interface yang ada dimanapun yaitu +[[//golang.org/pkg/fmt/#Stringer][`Stringer`]] +didefinisikan oleh paket +[[//golang.org/pkg/fmt/][`fmt`]]. type Stringer interface { String() string } -A `Stringer` is a type that can describe itself as a string. The `fmt` package -(and many others) look for this interface to print values. +Sebuah `Stringer` adalah suatu tipe yang mendeskripsikan dirinya sendiri +sebagai string. +Paket `fmt` (dan banyak lainnya) menggunakan interface ini untuk mencetak +nilai. .play methods/stringer.go -* Exercise: Stringers +* Latihan: Stringer -Make the `IPAddr` type implement `fmt.Stringer` to print the address as -a dotted quad. +Buat tipe `IPAddr` yang mengimplementasikan `fmt.Stringer` untuk mencetak alamat dengan empat tanda titik. -For instance, `IPAddr{1,`2,`3,`4}` should print as `"1.2.3.4"`. +Misalnya, `IPAddr{1,`2,`3,`4}` mengeluarkan `"1.2.3.4"`. .play methods/exercise-stringer.go -* Errors +* Error -Go programs express error state with `error` values. +Program Go mengekspresikan keadaan error dengan nilai `error`. -The `error` type is a built-in interface similar to `fmt.Stringer`: +Tipe `error` adalah interface buatan mirip dengan `fmt.Stringer`: type error interface { Error() string } -(As with `fmt.Stringer`, the `fmt` package looks for the `error` interface when -printing values.) +Seperti dengan `fmt.Stringer`, paket `fmt` mencari interface `error` saat mencetak nilai. -Functions often return an `error` value, and calling code should handle errors -by testing whether the error equals `nil`. +Fungsi terkadang mengembalikan nilai `error`, dan kode yang memanggilnya harus menangani error dengan memeriksa apakah error bernilai `nil`. i, err := strconv.Atoi("42") if err != nil { @@ -312,76 +331,89 @@ by testing whether the error equals `nil`. } fmt.Println("Converted integer:", i) -A nil `error` denotes success; a non-nil `error` denotes failure. +`error` yang nil menandakan sukses; `error` yang bukan-nil menandakan adanya kesalahan. .play methods/errors.go -* Exercise: Errors +* Latihan: Error -Copy your `Sqrt` function from the [[/flowcontrol/8][earlier exercise]] and modify it to return an `error` value. +Salin fungsi `Sqrt` anda dari +[[/flowcontrol/8][latihan sebelumnya]] +dan ubah untuk mengembalikan nilai `error`. -`Sqrt` should return a non-nil error value when given a negative number, as it doesn't support complex numbers. +`Sqrt` seharusnya mengembalikan nilai error bukan-nil saat diberikan angka negatif, karena tidak mendukung bilangan kompleks. -Create a new type +Buatlah tipe baru type ErrNegativeSqrt float64 -and make it an `error` by giving it a +dan buat dia sebagai `error` dengan memberikan method func (e ErrNegativeSqrt) Error() string -method such that `ErrNegativeSqrt(-2).Error()` returns `"cannot`Sqrt`negative`number:`-2"`. +sehingga `ErrNegativeSqrt(-2).Error()` mengembalikan `"cannot`Sqrt`negative`number:`-2"`. -*Note:* A call to `fmt.Sprint(e)` inside the `Error` method will send the program into an infinite loop. You can avoid this by converting `e` first: `fmt.Sprint(float64(e))`. Why? +*Catatan:* Pemanggilan `fmt.Sprint(e)` di dalam method `Error` akan membuat +program berulang tak henti. +Anda dapat menghindari hal tersebut dengan mengkonversi `e`: `fmt.Sprint(float64(e))`. +_Kenapa?_ -Change your `Sqrt` function to return an `ErrNegativeSqrt` value when given a negative number. +Ubah fungsi `Sqrt` mengembalikan nilai `ErrNegativeSqrt` saat diberikan nilai negatif. .play methods/exercise-errors.go -* Readers +* Reader -The `io` package specifies the `io.Reader` interface, -which represents the read end of a stream of data. +Paket `io` memiliki spesifikasi interface `io.Reader`, yang merepresentasikan berakhirnya pembacaan sebuah aliran data. -The Go standard library contains [[https://golang.org/search?q=Read#Global][many implementations]] of this interface, including files, network connections, compressors, ciphers, and others. +Standar pustaka Go memiliki +[[https://golang.org/search?q=Read#Global][banyak implementasi]] +dari interface tersebut, termasuk berkas, koneksi jaringan, kompresi, +_cipher_, dll. -The `io.Reader` interface has a `Read` method: +Interface `io.Reader` memiliki method `Read`: func (T) Read(b []byte) (n int, err error) -`Read` populates the given byte slice with data and returns the number of bytes -populated and an error value. It returns an `io.EOF` error when the stream -ends. +`Read` mengisi parameter slice byte dengan data dan mengembalikan jumlah byte yang diisi dan nilai errornya. +Ia mengembalikan error `io.EOF` saat aliran data berakhir. -The example code creates a +Contoh kode membuat sebuah [[//golang.org/pkg/strings/#Reader][`strings.Reader`]] -and consumes its output 8 bytes at a time. +dan memproses 8 bytes keluarannya. .play methods/reader.go -* Exercise: Readers +* Latihan: Reader -Implement a `Reader` type that emits an infinite stream of the ASCII character -`'A'`. +Implementasikan sebuah tipe `Reader` yang menghilangkan karakter ASCII `'A'` yang panjang. .play methods/exercise-reader.go -* Exercise: rot13Reader +* Latihan: rot13Reader -A common pattern is an [[https://golang.org/pkg/io/#Reader][io.Reader]] that wraps another `io.Reader`, modifying the stream in some way. +Pola umumnya adalah sebuah +[[https://golang.org/pkg/io/#Reader][io.Reader]] +yang membungkus `io.Reader` lainnya, memodifikasi aliran data dengan cara tertentu. -For example, the [[https://golang.org/pkg/compress/gzip/#NewReader][gzip.NewReader]] function takes an `io.Reader` (a stream of compressed data) and returns a `*gzip.Reader` that also implements `io.Reader` (a stream of the decompressed data). +Sebagai contohnya, fungsi +[[https://golang.org/pkg/compress/gzip/#NewReader][gzip.NewReader]] +mengambil `io.Reader` (aliran data terkompres) dan mengembalikan `*gzip.Reader` yang juga mengimplementasikan `io.Reader` (aliran data tak-terkompres). -Implement a `rot13Reader` that implements `io.Reader` and reads from an `io.Reader`, modifying the stream by applying the [[https://en.wikipedia.org/wiki/ROT13][rot13]] substitution cipher to all alphabetical characters. +Implementasikan `rot13Reader` yang mengimplementasikan `io.Reader` dengan +membaca dari `io.Reader`, modifikasi aliran data dengan menerapkan penyandian +[[https://en.wikipedia.org/wiki/ROT13][rot13]] +terhadap semua karakter alfabet. -The `rot13Reader` type is provided for you. -Make it an `io.Reader` by implementing its `Read` method. +Tipe `rot13Reader` telah disediakan untuk anda. +Buatlah ia menjadi `io.Reader` dengan mengimplementasikan method `Read`. .play methods/exercise-rot-reader.go -* Images +* Gambar -[[https://golang.org/pkg/image/#Image][Package image]] defines the `Image` interface: +[[http://golang.org/pkg/image/#Image][Paket image]] +mendefinisikan interface `Image`: package image @@ -391,32 +423,46 @@ Make it an `io.Reader` by implementing its `Read` method. At(x, y int) color.Color } -*Note*: the `Rectangle` return value of the `Bounds` method is actually an -[[https://golang.org/pkg/image/#Rectangle][`image.Rectangle`]], as the -declaration is inside package `image`. +*Catatan*: Nilai kembalian `Rectangle` dari method `Bounds` sebenarnya adalah +deklarasi +[[https://golang.org/pkg/image/#Rectangle][`image.Rectangle`]] +yang telah ada di dalam paket `image`. -(See [[https://golang.org/pkg/image/#Image][the documentation]] for all the details.) +(Lihat +[[https://golang.org/pkg/image/#Image][dokumentasi untuk paket Image]] +untuk lebih jelasnya.) -The `color.Color` and `color.Model` types are also interfaces, but we'll ignore that by using the predefined implementations `color.RGBA` and `color.RGBAModel`. These interfaces and types are specified by the [[https://golang.org/pkg/image/color/][image/color package]] +Tipe `color.Color` dan `color.Model` juga interface, tapi kita akan +menggunakan implementasi `color.RGBA` dan `color.RGBAModel`. +Interface dan tipe tersebut dispesifikasikan oleh +[[https://golang.org/pkg/image/color/][paket image/color]]. .play methods/images.go -* Exercise: Images +* Latihan: Gambar -Remember the [[/moretypes/18][picture generator]] you wrote earlier? Let's write another one, but this time it will return an implementation of `image.Image` instead of a slice of data. +Masih ingat generator gambar yang anda buat sebelumnya? +Mari kita buat satu lagi, tapi kali ini mengembalikan implementasi dari +`image.Image` bukan sebuah slice dari data. -Define your own `Image` type, implement [[https://golang.org/pkg/image/#Image][the necessary methods]], and call `pic.ShowImage`. +Definisikan tipe `Image` anda sendiri, kemudian implementasikan +[[https://golang.org/pkg/image/#Image][method-method yang dibutuhkan]] +, dan panggil `pic.ShowImage`. -`Bounds` should return a `image.Rectangle`, like `image.Rect(0,`0,`w,`h)`. +`Bounds` seharusnya mengembalikan `image.Rectangle`, seperti `image.Rect(0,`0,`w,`h)`. -`ColorModel` should return `color.RGBAModel`. +`ColorModel` seharusnya mengembalikan `color.RGBAModel`. -`At` should return a color; the value `v` in the last picture generator corresponds to `color.RGBA{v,`v,`255,`255}` in this one. +`At` seharusnya mengembalikan sebuah warna; +nilai `v` pada generator gambar berkoresponden dengan `color.RGBA{v,`v,`255,`255}`. .play methods/exercise-images.go -* Congratulations! +* Selamat! -You finished this lesson! +Anda telah menyelesaikan pelajaran ini! -You can go back to the list of [[/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]]. +Anda bisa kembali ke daftar +[[/list][modul]] +untuk melihat apa yang bisa dipelajari selanjutnya, atau meneruskan ke +[[javascript:click(".next-page")][pelajaran selanjutnya]]. diff --git a/content/moretypes.article b/content/moretypes.article index 5fe9401..71463f5 100644 --- a/content/moretypes.article +++ b/content/moretypes.article @@ -1,150 +1,149 @@ -More types: structs, slices, and maps. -Learn how to define types based on existing ones: this lesson covers structs, arrays, slices, and maps. +Tipe lanjut: struct, slice, dan map. +Belajar cara mendefinisikan tipe: pelajaran ini membahas struct, array, slice, dan map. -The Go Authors +Para Penggubah Go https://golang.org -* Pointers +* Pointer -Go has pointers. -A pointer holds the memory address of a value. +Go memiliki pointer. +Sebuah pointer menyimpan alamat dari sebuah variabel. -The type `*T` is a pointer to a `T` value. Its zero value is `nil`. +Tipe `*T` adalah pointer ke sebuah nilai `T`. +Nilai kosongnya adalah `nil`. var p *int -The `&` operator generates a pointer to its operand. +Operator `&` mengembalikan operan pointer dari variabel. i := 42 p = &i -The `*` operator denotes the pointer's underlying value. +Operator `*` mengembalikan nilai yang ditunjuk oleh pointer. - fmt.Println(*p) // read i through the pointer p - *p = 21 // set i through the pointer p + fmt.Println(*p) // baca nilai i lewat pointer p + *p = 21 // set nilai i lewat pointer p -This is known as "dereferencing" or "indirecting". +Cara ini disebut dengan "dereferencing" atau "indirecting". -Unlike C, Go has no pointer arithmetic. +Tidak seperti C, Go tidak memiliki fungsi aritmatika pada pointer. .play moretypes/pointers.go -* Structs +* Tipe data abstrak "struct" -A `struct` is a collection of fields. +Sebuah `struct` adalah kumpulan dari berbagai variabel. .play moretypes/structs.go -* Struct Fields +* Bagian dari struct -Struct fields are accessed using a dot. +Bagian dari struct diakses menggunakan sebuah titik. .play moretypes/struct-fields.go -* Pointers to structs +* Pointer ke struct -Struct fields can be accessed through a struct pointer. - -To access the field `X` of a struct when we have the struct pointer `p` we could -write `(*p).X`. -However, that notation is cumbersome, so the language permits us instead to -write just `p.X`, without the explicit dereference. +Untuk mengakses field `X` dari sebuah struct bila kita memiliki pointer ke +sebuah struct `p`, kita dapat menulisnya dengan `(*p).X`. +Namun, notasi tersebut tidak praktis, sehingga bahasa Go membolehkan kita +mengaksesnya langsung dengan menulis hanya `p.X`. .play moretypes/struct-pointers.go -* Struct Literals +* Inisialisasi struct -A struct literal denotes a newly allocated struct value by listing the values of its fields. +Sebuah `struct` bisa dibuat dengan mengisinya dengan nilai bagian-bagiannya. -You can list just a subset of fields by using the `Name:` syntax. (And the order of named fields is irrelevant.) +Anda juga bisa mengisi hanya sebagian dari kolom dengan menggunakan sintaks `Name:` (urutan dari bagian-bagiannya tidak berpengaruh). -The special prefix `&` returns a pointer to the struct value. +Prefik `&` mengembalikan sebuah pointer ke `struct`. .play moretypes/struct-literals.go -* Arrays +* Array -The type `[n]T` is an array of `n` values of type `T`. +Deklarasi tipe dengan `[n]T` adalah untuk array dengan jumlah `n` dan bertipe `T`. -The expression +Ekspresi var a [10]int -declares a variable `a` as an array of ten integers. +mendeklarasikan sebuah variabel `a` sebagai sebuah array dari sepuluh integer. -An array's length is part of its type, so arrays cannot be resized. -This seems limiting, but don't worry; -Go provides a convenient way of working with arrays. +Panjang sebuah array adalah bagian dari tipenya, jadi array tidak bisa diubah ukurannya. +Hal ini sepertinya membatasi, tapi jangan khawatir; +Go menyediakan cara yang mudah untuk bekerja dengan array. .play moretypes/array.go -* Slices +* Potongan ("slice") -An array has a fixed size. -A slice, on the other hand, is a dynamically-sized, -flexible view into the elements of an array. -In practice, slices are much more common than arrays. +Sebuah array memiliki ukuran yang tetap. +Sebuah slice ukurannya bisa dinamis, bisa mengacu secara fleksibel ke elemen +dalam sebuah array. +Dalam praktiknya, slice lebih sering digunakan daripada array. -The type `[]T` is a slice with elements of type `T`. +Type `[]T` adalah sebuah slice dengan elemen bertipe `T`. -A slice is formed by specifying two indices, a low and -high bound, separated by a colon: +Sebuah slice dibentuk dengan menspesifikasikan dua indeks, batas bawah dan +batas atas, dipisahkan oleh sebuah tanda titik-dua: - a[low : high] + a[bawah : atas] -This selects a half-open range which includes the first -element, but excludes the last one. +Notasi di atas memotong rentang dari slice `a` yang mengikutkan elemen +`bawah`, tapi tidak memasukan bagian terakhir (atas). -The following expression creates a slice which includes -elements 1 through 3 of `a`: +Ekspresi berikut membuat sebuah slice yang mengikutkan elemen 1 sampai 3 dari +slice `a`: a[1:4] .play moretypes/slices.go -* Slices are like references to arrays - -A slice does not store any data, -it just describes a section of an underlying array. +* Slice adalah referensi ke array -Changing the elements of a slice modifies the -corresponding elements of its underlying array. +Sebuah slice tidak menyimpan data, ia hanya mendeskripsikan sebuah bagian dari +array. -Other slices that share the same underlying array will see those changes. +Mengubah nilai dari elemen dari sebuah slice juga mengubah elemen di +array-nya. .play moretypes/slices-pointers.go -* Slice literals +* Sifat Dasar Slice -A slice literal is like an array literal without the length. +Sebuah slice mirip dengan array tanpa panjang. -This is an array literal: +Berikut ini adalah sebuah array: [3]bool{true, true, false} -And this creates the same array as above, -then builds a slice that references it: +Dan berikut ini membuat array yang sama seperti di atas, kemudian membuat +sebuah slice yang mengacu kepadanya: []bool{true, true, false} .play moretypes/slice-literals.go -* Slice defaults +* Nilai Default Slice -When slicing, you may omit the high or low bounds to use their defaults instead. +Saat memotong, anda bisa mengindahkan batas bawah atau atas sehingga Go akan +menggunakan nilai default-nya. -The default is zero for the low bound and the length of the slice for the high bound. +Nilai default-nya adalah nol untuk batas bawah dan panjang dari slice untuk +batas atas. -For the array +Untuk sebuah array berikut, var a [10]int -these slice expressions are equivalent: +ekspresi slice berikut adalah setara: a[0:10] a[:10] @@ -154,47 +153,47 @@ these slice expressions are equivalent: .play moretypes/slice-bounds.go -* Slice length and capacity +* Panjang dan Kapasitas Slice -A slice has both a _length_ and a _capacity_. +Sebuah slice memiliki _panjang_ dan _kapasitas_. -The length of a slice is the number of elements it contains. +Panjang dari sebuah slice yaitu jumlah dari elemen yang dimilikinya. -The capacity of a slice is the number of elements in the underlying array, -counting from the first element in the slice. +Kapasitas dari sebuah slice adalah jumlah dari elemen array yang dikandungnya, +dihitung dari elemen pertama di dalam slice. -The length and capacity of a slice `s` can be obtained using the expressions -`len(s)` and `cap(s)`. +Panjang dan kapasitas dari sebuah slice `s` dapat diambil dengan menggunakan +ekspresi `len(s)` dan `cap(s)`. -You can extend a slice's length by re-slicing it, -provided it has sufficient capacity. -Try changing one of the slice operations in the example program to extend it -beyond its capacity and see what happens. +Anda bisa memperluas panjang dari sebuah slice dengan me-motong-ulang, bila +kapasitasnya cukup. +Coba ubah salah satu operasi slice di contoh program sebelah untuk +memperluasnya melebihi kapasitasnya dan lihat apa yang terjadi. .play moretypes/slice-len-cap.go -* Nil slices +* Slice kosong -The zero value of a slice is `nil`. +Nilai nol dari slice adalah `nil`. -A nil slice has a length and capacity of 0 -and has no underlying array. +Slice yang kosong memiliki panjang dan kapasitas 0, dan tidak memiliki array +di dalamnya. .play moretypes/nil-slices.go -* Creating a slice with make +* Membuat slice dengan `make` -Slices can be created with the built-in `make` function; -this is how you create dynamically-sized arrays. +Slice dapat dibuat dengan fungsi `make`; +dengan fungsi tersebut anda bisa membuat array dengan ukuran yang dinamis. -The `make` function allocates a zeroed array -and returns a slice that refers to that array: +Fungsi `make` mengalokasikan array yang dikosongkan dan mengembalikan sebuah +slice yang mengacu pada array tersebut. a := make([]int, 5) // len(a)=5 -To specify a capacity, pass a third argument to `make`: +Untuk menentukan kapasitasnya, tambahkan argumen ketiga pada `make`: b := make([]int, 0, 5) // len(b)=0, cap(b)=5 @@ -204,158 +203,188 @@ To specify a capacity, pass a third argument to `make`: .play moretypes/making-slices.go -* Slices of slices +* Slice dari slice -Slices can contain any type, including other slices. +Slice bisa mengandung tipe apapun, termasuk slice lainnya. .play moretypes/slices-of-slice.go -* Appending to a slice +* Menambahkan elemen ke slice -It is common to append new elements to a slice, and so Go provides a built-in -`append` function. The [[https://golang.org/pkg/builtin/#append][documentation]] -of the built-in package describes `append`. +Sangat umum untuk menambahkan elemen ke slice, sehingga Go menyediakan fungsi +`append`. +[[https://golang.org/pkg/builtin/#append][Dokumentasinya]] +menjelaskan lebih lanjut dari fungsi `append`. func append(s []T, vs ...T) []T -The first parameter `s` of `append` is a slice of type `T`, and the rest are -`T` values to append to the slice. +Parameter pertama `s` dari `append` adalah sebuah slice dengan tipe `T`, dan +sisanya adalah nilai `T` yang akan ditambahkan ke slice. -The resulting value of `append` is a slice containing all the elements of the -original slice plus the provided values. +Hasil dari `append` yaitu sebuah slice yang berisi semua elemen dari slice +awal berikut dengan nilai yang ditambahkan. -If the backing array of `s` is too small to fit all the given values a bigger -array will be allocated. The returned slice will point to the newly allocated -array. +Jika array awal `s` terlalu kecil untuk nilai yang ditambahkan, maka array +yang lebih besar akan dialokasikan. +Kembaliannya yaitu slice yang merujuk ke array yang baru dialokasikan. -(To learn more about slices, read the [[https://blog.golang.org/go-slices-usage-and-internals][Slices: usage and internals]] article.) +(Untuk belajar lebih lanjut tentang slice, bacalah artikel +[[https://blog.golang.org/go-slices-usage-and-internals][Slices: usage and +internals]].) .play moretypes/append.go -* Range +* Rentang ("range") -The `range` form of the `for` loop iterates over a slice or map. +Perintah `range` pada pengulangan `for` mengiterasi sebuah slice atau map. When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index. .play moretypes/range.go -* Range continued -You can skip the index or value by assigning to `_`. +* Rentang lanjutan + +Anda bisa melewati indeks atau nilai dengan operator `_`. for i, _ := range pow for _, value := range pow -If you only want the index, you can omit the second variable. +Jika anda hanya menginginkan indeks saja, variabel kedua bisa dihilangkan. for i := range pow .play moretypes/range-continued.go -* Exercise: Slices +* Latihan: Slice + +Implementasikan `Pic`. +Fungsi tersebut harus mengembalikan sebuah slice dengan panjang `dy`, setiap +elemennya merupakan sebuah slice `dx` 8-bit unsigned integer. +Saat anda menjalankan program, ia akan menampilkan gambar anda, +mengiterpretasikan nilai integer dengan warna abu-abu. -Implement `Pic`. It should return a slice of length `dy`, each element of which is a slice of `dx` 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values. +Pilihan gambarnya terserah anda. +Fungsi menarik yang bisa diikutkan berupa `(x+y)/2`, `x*y`, dan `x^y`. -The choice of image is up to you. Interesting functions include `(x+y)/2`, `x*y`, and `x^y`. +Petunjuk: -(You need to use a loop to allocate each `[]uint8` inside the `[][]uint8`.) +- Anda membutuhkan penggunaan sebuah pengulangan untuk mengalokasi `[]uint8` di dalam `[][]uint8`. -(Use `uint8(intValue)` to convert between types.) +- Gunakan `uint8(intValue)` untuk mengkonversi antara tipe. .play moretypes/exercise-slices.go -* Maps -A map maps keys to values. +* Map + +Sebuah map memetakan sebuah kunci (_key_) dengan nilainya. -The zero value of a map is `nil`. -A `nil` map has no keys, nor can keys be added. +Nilai kosong dari sebuah map adalah `nil`. +Sebuah map yang `nil` tidak memiliki kunci, tidak juga dapat ditambahkan kunci +baru. -The `make` function returns a map of the given type, -initialized and ready for use. +Fungsi `make` mengembalikan sebuah map dengan tipenya, diinisialisasi dan siap +untuk digunakan. .play moretypes/maps.go -* Map literals +* Penggunaan Map -Map literals are like struct literals, but the keys are required. +Penggunaan map seperti pada penggunaan struct, tapi dengan membubuhkan key-nya. .play moretypes/map-literals.go -* Map literals continued +* Penggunaan map lanjutan -If the top-level type is just a type name, you can omit it from the elements of the literal. +Jika level teratas dari tipe hanya nama tipe, anda bisa menghilangkannya dari inisialisasi elemen map. .play moretypes/map-literals-continued.go -* Mutating Maps +* Operasi map -Insert or update an element in map `m`: +Pengisian atau mengubah elemen dalam map `m`: m[key] = elem -Retrieve an element: +Mengambil elemen: elem = m[key] -Delete an element: +Menghapus elemen: delete(m, key) -Test that a key is present with a two-value assignment: +Menguji apakah sebuah key ada dalam map: elem, ok = m[key] -If `key` is in `m`, `ok` is `true`. If not, `ok` is `false`. +Jika `key` ada dalam `m`, `ok` bernilai `true`. +Jika tidak ada, `ok` bernilai `false`. -If `key` is not in the map, then `elem` is the zero value for the map's element type. +Jika `key` tidak ada dalam map, maka `elem` berisi nilai kosong sesuai dengan +tipe elemen. -*Note:* If `elem` or `ok` have not yet been declared you could use a short declaration form: +*Catatan:* Jika `elem` atau `ok` belum dideklarasikan anda bisa menggunakan +bentuk deklarasi singkat berikut: elem, ok := m[key] .play moretypes/mutating-maps.go -* Exercise: Maps +* Latihan: map -Implement `WordCount`. It should return a map of the counts of each “word” in the string `s`. The `wc.Test` function runs a test suite against the provided function and prints success or failure. +Implementasikan `WordCount`. +Fungsi tersebut mengembalikan sebuah map dari penghitungan setiap "kata" di dalam string `s`. +Fungsi `wc.Test` menjalankan pengujian terhadap fungsi yang diberikan dan mencetak sukses atau salah. -You might find [[https://golang.org/pkg/strings/#Fields][strings.Fields]] helpful. +Anda mungkin menemukan artikel berikut +[[https://golang.org/pkg/strings/#Fields][strings.Fields]] +membantu anda. .play moretypes/exercise-maps.go -* Function values +* Nilai Fungsi -Functions are values too. They can be passed around just like other values. +Fungsi adalah suatu nilai juga. +Fungsi dapat dikirimkan kemanapun seperti nilai lainnya. -Function values may be used as function arguments and return values. +Nilai fungsi bisa digunakan sebagai argumen pada fungsi dan sebagai nilai +kembalian. .play moretypes/function-values.go -* Function closures +* Fungsi closure -Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables. +Fungsi pada Go bisa _closure_. +_Closure_ adalah sebuah nilai fungsi yang merujuk variabel dari blok fungsinya. +Fungsi closure bisa mengakses dan mengisi variabel yang dirujuk; +dalam artian fungsi tersebut "terikat" ke variabel. -For example, the `adder` function returns a closure. Each closure is bound to its own `sum` variable. +Sebagai contohnya, fungsi `adder` mengembalikan sebuah closure. +Setiap closure terikat dengan variabel `sum` -nya sendiri. .play moretypes/function-closures.go -* Exercise: Fibonacci closure +* Latihan: Fibonacci dengan closure -Let's have some fun with functions. +Mari bermain dengan fungsi. -Implement a `fibonacci` function that returns a function (a closure) that -returns successive [[https://en.wikipedia.org/wiki/Fibonacci_number][fibonacci numbers]] +Implementasikan sebuah fungsi `fibonacci` yang mengembalikan sebuah fungsi +(closure) yang mengembalikan +[[https://en.wikipedia.org/wiki/Fibonacci_number][bilangan fibonacci]] (0, 1, 1, 2, 3, 5, ...). .play moretypes/exercise-fibonacci-closure.go -* Congratulations! +* Selamat! -You finished this lesson! +Anda telah menyelesaikan pelajaran ini! -You can go back to the list of [[/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]]. +Anda bisa kembali ke daftar +[[/list][modul]] +untuk melihat apa yang bisa dipelajari selanjutnya, atau meneruskan dengan +[[javascript:click(".next-page")][pelajaran selanjutnya]]. diff --git a/content/welcome.article b/content/welcome.article index 51aa919..1195357 100644 --- a/content/welcome.article +++ b/content/welcome.article @@ -1,51 +1,65 @@ -Welcome! -Learn how to use this tour: including how to navigate the different lessons and how to run code. +Selamat datang! +Belajar cara menggunakan tur ini: termasuk cara navigasi pelajaran dan cara menjalankan kode. -The Go Authors +Para Penggubah Go https://golang.org -* Hello, 世界 +* Halo, 世界 -Welcome to a tour of the [[https://golang.org/][Go programming language]]. +Selamat datang di tur +[[https://golang.org/][bahasa pemrograman Go]] +. -The tour is divided into a list of modules that you can -access by clicking on -[[javascript:highlight(".logo")][A Tour of Go]] on the top left of the page. +Tur ini dibagi menjadi beberapa modul yang dapat anda akses dengan mengklik pada +[[javascript:highlight(".logo")][Tur Go]] +di bagian kiri atas halaman. -You can also view the table of contents at any time by clicking on the [[javascript:highlightAndClick(".nav")][menu]] on the top right of the page. +Anda juga dapat setiap saat melihat daftar isi dengan mengklik pada +[[javascript:highlightAndClick(".nav")][menu]] +di kanan atas halaman. -Throughout the tour you will find a series of slides and exercises for you -to complete. +Selama tur ini anda akan menemukan sekumpulan slide dan latihan untuk anda kerjakan. -You can navigate through them using +Anda bisa menavigasinya lewat -- [[javascript:highlight(".prev-page")]["previous"]] or `PageUp` to go to the previous page, +- [[javascript:highlight(".prev-page")]["sebelum"]] +atau `PageUp` untuk kembali ke halaman sebelumnya, -- [[javascript:highlight(".next-page")]["next"]] or `PageDown` to go to the next page. +- [[javascript:highlight(".next-page")]["selanjutnya"]] +atau `PageDown` untuk ke halaman selanjutnya. -The tour is interactive. Click the -[[javascript:highlightAndClick("#run")][Run]] button now -(or press `Shift` + `Enter`) to compile and run the program on -#appengine: a remote server. -your computer. -The result is displayed below the code. +Tur ini interaktif. Klik pada tombol +[[javascript:highlightAndClick("#run")][Jalankan]] +sekarang (atau tekan `Shift` + `Enter`) untuk mengkompilasi dan menjalankan +program pada +#appengine: server. +komputer anda. +Hasilnya ditampilkan di bawah kode. -These example programs demonstrate different aspects of Go. The programs in the tour are meant to be starting points for your own experimentation. +Contoh program tersebut menampilkan aspek dari Go. +Program yang ada di tur ditujukan sebagai titik awal bagi eksperimen anda. -Edit the program and run it again. +Ubah program tersebut dan jalankan lagi. -When you click on [[javascript:highlightAndClick("#format")][Format]] -(shortcut: `Ctrl` + `Enter`), the text in the editor is formatted using the -[[https://golang.org/cmd/gofmt/][gofmt]] tool. You can switch syntax highlighting on and off -by clicking on the [[javascript:highlightAndClick(".syntax-checkbox")][syntax]] button. +Saat anda mengklik pada tombol +[[javascript:highlightAndClick("#format")][Format]] +(atau `Ctrl` + `Enter`), teks di bagian editor akan diformat menggunakan alat +[[https://golang.org/cmd/gofmt/][gofmt]]. +Anda bisa menghidup atau mematikan sintaks dengan mengklik pada tombol +[[javascript:highlightAndClick(".syntax-checkbox")][sintaks]] -When you're ready to move on, click the [[javascript:highlightAndClick(".next-page")][right arrow]] below or type the `PageDown` key. +Anda bisa mengaktifkan pewarnaan sintaks dengan mengklik pada tombol +[[javascript:highlightAndClick(".syntax-checkbox"][sintaks]]. + +Saat anda selesai, klik +[[javascript:highlightAndClick(".next-page")][panah kanan]] +di bawah atau tekan `PageDown`. .play welcome/hello.go -* Go local +* Go Lokal -The tour is available in other languages: +Tur ini tersedia dalam beberapa bahasa: - [[https://go-tour-ar.appspot.com/][Arabic — العربية]] - [[https://go-tour-br.appspot.com/][Brazilian Portuguese — Português do Brasil]] @@ -55,8 +69,6 @@ The tour is available in other languages: - [[https://go-tour-cz.appspot.com/][Czech — Česky]] - [[https://go-tour-fr.appspot.com/][French — Français]] - [[https://go-tour-de.appspot.com/][German — Deutsch]] -- [[https://go-tour-he.appspot.com/][Hebrew — עִבְרִית]] -- [[https://go-tour-id2.appspot.com/][Indonesian — Bahasa Indonesia]] - [[https://go-tour-ita.appspot.com/][Italian — Italiano]] - [[https://go-tour-jp.appspot.com/][Japanese — 日本語]] - [[https://go-tour-kr.appspot.com/][Korean — 한국어]] @@ -68,49 +80,61 @@ The tour is available in other languages: - [[https://go-tour-ua.appspot.com/][Ukrainian — Українська]] - [[https://go-tour-uz.appspot.com/][Uzbek — Ўзбекча]] -Click the [[javascript:highlightAndClick(".next-page")]["next"]] button or type `PageDown` to continue. +Klik tombol +[[javascript:highlightAndClick(".next-page")]["selanjutnya"]] +atau tekan `PageDown` untuk melanjutkan. #appengine: * Go offline (optional) #appengine: -#appengine: This tour is also available as a stand-alone program that you can use -#appengine: without access to the internet. It builds and runs the code samples on -#appengine: your own machine. +#appengine: Tur ini juga tersedia dalam program yang berjalan tersendiri yang +#appengine: dapat anda gunakan tanpa akses internet. +#appengine: +#appengine: Tur yang berjalan sendiri lebih cepat, karena ia membuat and +#appengine: menjalankan sampel program di mesin anda sendiri. #appengine: -#appengine: To run the tour locally, you'll need to first -#appengine: [[https://golang.org/doc/install][install Go]] and then run: +#appengine: Untuk dapat menjalakan tur secara lokal, pertama +#appengine: [[https://golang.org/dl/][unduh and pasang Go]] +#appengine: kemudian jalankan program tour dengan cara, #appengine: #appengine: go get golang.org/x/tour #appengine: -#appengine: This will place a `tour` binary in your -#appengine: [[https://golang.org/doc/code.html#Workspaces][workspace]]'s `bin` directory. -#appengine: When you run the tour program, it will open a web browser displaying -#appengine: your local version of the tour. +#appengine: Program `tour` akan membuka peramban web yang menampilkan versi +#appengine: lokal dari tur. #appengine: -#appengine: Of course, you can continue to take the tour through this web site. +#appengine: Atau, tentu saja, anda bisa melanjutkan tur di situs ini. -#appengine: * The Go Playground +#appengine: * Go Playground #appengine: -#appengine: This tour is built atop the [[https://play.golang.org/][Go Playground]], a -#appengine: web service that runs on [[https://golang.org/][golang.org]]'s servers. +#appengine: Tur ini dibuat dengan +#appengine: [[https://play.golang.org/][Go Playground]] +#appengine: , sebuah layanan web yang berjalan di atas server +#appengine: [[https://golang.org/][golang.org]]. #appengine: -#appengine: The service receives a Go program, compiles, links, and runs the program inside -#appengine: a sandbox, then returns the output. +#appengine: Layanan tersebut menerima program Go, mengkompilasi, dan +#appengine: menjalankan program di dalam _sandbox_, dan mengembalikan +#appengine: keluaran. #appengine: -#appengine: There are limitations to the programs that can be run in the playground: +#appengine: Ada beberapa batasan untuk program yang berjalan di _playground_: #appengine: -#appengine: - In the playground the time begins at 2009-11-10 23:00:00 UTC (determining the significance of this date is an exercise for the reader). This makes it easier to cache programs by giving them deterministic output. +#appengine: - Di _playground_ waktu dimulai dari 2009-11-10 23:00:00 UTC +#appengine: (mengetahui kenapa menggunakan tanggal tersebut adalah latihan +#appengine: bagi pembaca). +#appengine: Hal ini membuat program lebih mudah di- _cache_ dengan memberikan +#appengine: nilai keluaran yang pasti. #appengine: -#appengine: - There are also limits on execution time and on CPU and memory usage, and the program cannot access external network hosts. +#appengine: - Waktu eksekusi, penggunaan CPU, dan _memory_ juga memiliki +#appengine: batasan, dan program tidak dapat mengakses jaringan eksternal. #appengine: -#appengine: The playground uses the latest stable release of Go. +#appengine: _Playground_ menggunakan rilis stabil dari Go. #appengine: -#appengine: Read "[[https://blog.golang.org/playground][Inside the Go Playground]]" to learn more. +#appengine: Bacalah " +#appengine: [[https://blog.golang.org/playground][Inside the Go Playground]] +#appengine: " untuk belajar lebih lanjut. #appengine: #appengine: .play welcome/sandbox.go -* Congratulations +* Selamat -You've finished the first module of the tour! +Anda telah menyelesaikan modul pertama dari tur! -Now click on [[javascript:highlightAndClick(".logo")][A Tour of Go]] to find out what else -you can learn about Go, or go directly to the [[javascript:click('.next-page')][next lesson]]. +Sekarang klik pada [[javascript:highlightAndClick(".logo")][Sebuah Tur dari Go]] untuk menemukan apa saja yang dapat anda pelajari tentang Go, atau langsung ke [[javascript:click(".next-page")][pelajaran selanjutnya]]. diff --git a/static/js/values.js b/static/js/values.js index 1c24ddc..de73e7f 100644 --- a/static/js/values.js +++ b/static/js/values.js @@ -1,4 +1,4 @@ -/* Copyright 2012 The Go Authors. All rights reserved. +/* Copyright 2012-2015 The Go Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ @@ -9,44 +9,44 @@ angular.module('tour.values', []). // List of modules with description and lessons in it. value('tableOfContents', [{ 'id': 'mechanics', - 'title': 'Using the tour', - 'description': '<p>Welcome to a tour of the <a href="https://golang.org">Go programming language</a>. The tour covers the most important features of the language, mainly:</p>', + 'title': 'Penggunaan Tur', + 'description': '<p>Selamat datang di tur <a href="https://golang.org">bahasa pemrograman Go</a>. Tur ini melingkupi fitur paling penting dari bahasa, pada umumnya:</p>', 'lessons': ['welcome'] }, { 'id': 'basics', - 'title': 'Basics', - 'description': '<p>The starting point, learn all the basics of the language.</p><p>Declaring variables, calling functions, and all the things you need to know before moving to the next lessons.</p>', + 'title': 'Dasar', + 'description': '<p>Langkah awal, pelajari semua dasar bahasa.</p><p>Deklarasi variabel, pemanggilan fungsi, dan semua hal yang perlu anda ketahui sebelum pindah ke pelajaran selanjutnya.</p>', 'lessons': ['basics', 'flowcontrol', 'moretypes'] }, { 'id': 'methods', - 'title': 'Methods and interfaces', - 'description': '<p>Learn how to define methods on types, how to declare interfaces, and how to put everything together.</p>', + 'title': 'Method dan interface', + 'description': '<p>Belajar cara mendefinisikan method pada tipe, cara deklarasi interface, dan cara menggabungkan keduanya.</p>', 'lessons': ['methods'] }, { 'id': 'concurrency', - 'title': 'Concurrency', - 'description': '<p>Go provides concurrency features as part of the core language.</p><p>This module goes over goroutines and channels, and how they are used to implement different concurrency patterns.</p>', + 'title': 'Konkurensi', + 'description': '<p>Go menyediakan fitur konkurensi sebagai bagian dari inti bahasa.</p><p>Modul ini ada pada goroutines dan channels, dan cara menggunakannya pada pola konkurensi yang berbeda.</p>', 'lessons': ['concurrency'] }]). // translation value('translation', { - 'off': 'off', - 'on': 'on', - 'syntax': 'Syntax-Highlighting', - 'lineno': 'Line-Numbers', + 'off': 'hidup', + 'on': 'nyala', + 'syntax': 'Penekanan-Sintaks', + 'lineno': 'Nomor-Baris', 'reset': 'Reset Slide', - 'format': 'Format Source Code', - 'kill': 'Kill Program', - 'run': 'Run', - 'compile': 'Compile and Run', - 'more': 'Options', - 'toc': 'Table of Contents', - 'prev': 'Previous', - 'next': 'Next', - 'waiting': 'Waiting for remote server...', - 'errcomm': 'Error communicating with remote server.', - 'submit-feedback': 'Send feedback about this page', + 'format': 'Format Sumber Kode', + 'kill': 'Matikan Program', + 'run': 'Jalankan', + 'compile': 'Kompilasi dan Jalankan', + 'more': 'Opsi', + 'toc': 'Daftar Isi', + 'prev': 'Sebelumnya', + 'next': 'Selanjutnya', + 'waiting': 'Menunggu server...', + 'errcomm': 'Kesalahan komunikasi dengan server.', + 'submit-feedback': 'Kirim umpan-balik tentang halaman ini', // GitHub issue template: update repo and messaging when translating. 'github-repo': 'github.com/golang/tour', |
