DEV Community

Cover image for Golang perk series : (typed) arrays – JS vs. GO #3
Lukas Gaucas
Lukas Gaucas

Posted on • Updated on

Golang perk series : (typed) arrays – JS vs. GO #3

ARRAYS

  • UNTYPED ARRAYS

In JavaScript :

var nil_ = []; /* implicitly as type of int (use TS if you want to be sure) */
console.log(`${nil_.length == 0}\n`) // true
Enter fullscreen mode Exit fullscreen mode

In Golang :

var nil_ []int
fmt.Println(len(nil_) == 0) // true
Enter fullscreen mode Exit fullscreen mode

  • TYPED ARRAYS
    • declarations :
  • TYPED ARRAYS
    • views :

In JavaScript :

/*var*/ primes = new ArrayBuffer(8)
/*var*/ uint8 = new Uint16Array(primes)
/*var*/ sliced_primes = uint8.slice()
console.log(sliced_primes) // Uint16Array(4) [0, 0, 0, 0, buffer: ArrayBuffer(8), byteLength: 8, byteOffset: 0, length: 4, Symbol(Symbol.toStringTag): 'Uint16Array']
Enter fullscreen mode Exit fullscreen mode

In Golang :

func main() {
        primes := [4]int{}
    var sliced_primes []int = primes[0:len(primes)]
    fmt.Println(sliced_primes)
}
// try oneself on : @https://go.dev/play/
Enter fullscreen mode Exit fullscreen mode

NOTE : In JavaScript TypedArrays are limited of one specific type you choose to have in the container , whereas DataView (heterogenous data in fancy terms) can be used as a "translator" eliminating boundaries "of one type" for TypedArrays (homogenous data in fancy terms) .

TIP : with reference to explanation above , in Node.js
runtime we would use Buffer.from() !


  • Slicing the arrays :

In JavaScript :

  // Task : slice each season's months into dedicated variable & print it :
function main(){
  var full_year = ["Jan", "Feb", "March", "April", "May", "June", "July","August", "September", "October", "November", "December",]
  var winter = full_year.slice(0,2) winter.unshift(full_year[11])
  var spring = full_year.slice(2,5)
  var summer = full_year.slice(5,8)
  var autumn = full_year.slice(8,11)
  console.log(full_year, winter, spring, summer, autumn)
}
main()
Enter fullscreen mode Exit fullscreen mode

In Golang :

package main 

import (
  . "fmt"
)

func main(){
  full_year := []string{"Jan", "Feb", "March", "April", "May", "June", "July","August", "September", "October", "November", "December",}

  /* --- */

  // Task : slice each season's months into dedicated variable & print it :
  var winter = append([]string{}, full_year[11], full_year[0], full_year[1])
  var spring = full_year[2:5]
  var summer = full_year[6:9]
  var autumn = full_year[9:12]
  Println(full_year, winter, spring, summer, autumn)
} 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)