Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

see_its_a_new_array

package main

import "fmt"

func main() {
    x := &[10]int{1,2,3,4,5,6,7,8,9,10}
    y := x[2:5]
    z := y[:1:2]
    
    fmt.Printf("cap %v, array: %v\ncap y: %v, slice: %v\ncap z: %v, slice: %v\n", cap(x) , *x, cap(y), y, cap(z), z)
    z = append(z, 0, 0, 0, 0, 0)
    fmt.Printf("cap %v, array: %v\ncap y: %v, slice: %v\ncap z: %v, slice: %v\n", cap(x) , *x, cap(y), y, cap(z), z)
}

Go Passing pointers to functions

package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 100
   var b int= 200

   fmt.Printf("Before swap, value of a : %d\n", a )
   fmt.Printf("Before swap, value of b : %d\n", b )

   /* calling a function to swap the values.
   * &a indicates pointer to a ie. address of variable a and 
   * &b indicates pointer to b ie. address of variable b.
   */
   swap(&a, &b);

   fmt.Printf("After swap, value of a : %d\n", a )
   fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
   var temp int
   temp = *x    /* save the value at address x */
   *x = *y      /* put y into x */
   *y = temp    /* put temp into y */
}

Go Creating Strings

package main

import "fmt"

func main() {
   var greeting =  "Hello world!"
   
   fmt.Printf("normal string: ")
   fmt.Printf("%s", greeting)
   fmt.Printf("\n")
   fmt.Printf("hex bytes: ")
   
   for i := 0; i < len(greeting); i++ {
       fmt.Printf("%x ", greeting[i])
   }
   fmt.Printf("\n")
   
   const sampleText = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98" 
   /*q flag escapes unprintable characters, with + flag it escapses non-ascii 
   characters as well to make output unambigous  
   */
   fmt.Printf("quoted string: ")
   fmt.Printf("%+q", sampleText)
   fmt.Printf("\n")  
}

Go Method

import (
   "fmt" 
   "math" 
)

/* define a circle */
type Circle struct {
   x,y,radius float64
}

/* define a method for circle */
func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

func main(){
   circle := Circle{x:0, y:0, radius:5}
   fmt.Printf("Circle area: %f", circle.area())
}

Go Returning Multiple Values

package main

import "fmt"

func swap(x, y string) (string, string) {
   return y, x
}
func main() {
    
// call by reference
   a, b := swap("Ali", "Mohammad")
   fmt.Println(a, b)
 
 
// call by value
   var a2 = "Ali2"
   var b2 = "Mohammad2" 
   swap(a,b)
   fmt.Println(a2, b2)


// call by value   
   a3, b3 := "Ali3", "Mohammad3"
   swap(a,b)
   fmt.Println(a3,b3)

}

Execute GO Language Online

package main

import (
    "fmt"
    "reflect"
)

func main() {
    // Will print 'int'
    anInt := 1234
    fmt.Printf("%T\n", anInt)

    // Will print 'string'
    aString := "Hello World"
    fmt.Printf("%T\n", aString)

    // Will print 'float64'
    aFloat := 3.14
    fmt.Printf("%T\n", aFloat)
    

    fmt.Println(reflect.TypeOf(anInt).String())
}

SoHoanHao

package main

import (
  "fmt"
  "bufio"
  "os"
  "strconv"
)

func TimUocSo(n int) []int {
  var res []int

  for i := 1; i <= n/2; i++ {
    if n%i == 0 {
      res = append(res, i)
    }
  }

  return res
}

func KTSoHoanHao(n int) bool {
  UocSo := TimUocSo(n)
  for _, v := range UocSo {
    n -= v
  }

  if n == 0 {
    return true
  }

  return false
}

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    Input := scanner.Text()
    ID, err := strconv.Atoi(Input)
    if err != nil {
        panic(err)
    }
  
  if KTSoHoanHao(ID) {
    fmt.Printf("%d la so hoan hao !\n", ID)
  } else {
    fmt.Printf("%d khong phai la so hoan hao\n", ID)
  }
}

lucky lottery id generator

package main

import (
	"fmt"
	"math/big"
	"math/rand"
)

func main() {
	tx := "00000000000000000002bf59c3d819e4666909512803cf28113ff09849b4545e"
	total := int64(10) // type in maxmium lottery nubmer here

	fmt.Printf("lucy lottery id: %d\n", Rand(tx, total))
}

// @param tx:
//  from site: https://btc.com/block 
//  The hash of the first block generated after UTC 08:00AM. On 2018-10-11, for example tx is 00000000000000000011f41d5df213f232c1778730e834635eb836276fc184bf
//  which from block: https://btc.com/00000000000000000011f41d5df213f232c1778730e834635eb836276fc184bf
// @param total 
//  the total luck lottery numbers generated duratation the non-mining minutes
//
func Rand(tx string, total int64) int64 {
	v, _ := big.NewInt(0).SetString(tx, 16)
	seed := v.Int64() // ignore overflow
	source := rand.NewSource(seed)
	r := rand.New(source)

	return r.Int63n(int64(total)) + 1 // +1 because our lottery numbers starts from 1
}

Test

package main

import "fmt"

func main() {
   fmt.Println("hello, world\n")
   var a = 4
   var b = 2
   var total = a + b
   fmt.Println(total)
}

Execute GO Language Online

package main

import (
    "crypto/aes"
    //"crypto/cipher"
    //"crypto/rand"
    "crypto/sha256"
    "fmt"
    "log"
    //"io"
    "encoding/hex"
    //"io/ioutil"
    "os"
)

func encrypt() {
     //block size for SHA-256 is 64 bytes
    blockSize := 64
    keyMacHex := "6b6579" //TODO: parse from command line (last 16 bytes)
    
    //parse hexadecimal key string into byte slice
    keyMac, err := hex.DecodeString(keyMacHex)
    if err != nil {
        log.Fatal(err)
    }
    
    //generate inner and outer padded key
    var outPad []byte
    var inPad []byte
    for i := 0; i < blockSize; i++ {
        //XOR bits of key and pads (key is assumed padded with 0s if too short)
        if i < len(keyMac) {
            outPad = append(outPad, keyMac[i] ^ '\x5c')
            inPad = append(inPad, keyMac[i] ^ '\x36')
        } else {
            outPad = append(outPad, '\x00' ^ '\x5c')
            inPad = append(inPad, '\x00' ^ '\x36')
        }
    }
    msgHex := fmt.Sprintf("%x", "The quick brown fox jumps over the lazy dog") //TODO: parse from file
    
    //parse hexadecimal message string into byte slice
    msg, err := hex.DecodeString(msgHex)
    if err != nil {
        log.Fatal(err)
    }
    
    //two hash objects for the inner and outer hash
    h256_inner := sha256.New()
    h256_outer := sha256.New()
    
    //hash the concatenation of inner pad and message
    inMsg := append(inPad, msg...)
    h256_inner.Write(inMsg)
    
    //hash the concatenation of outer pad and inner hash 
    outMsg := append(outPad, h256_inner.Sum(nil)...)
    h256_outer.Write(outMsg)
    
    //get final 32-byte MAC tag
    mac := h256_outer.Sum(nil)
    
    //concatenate message and MAC tag
    mPad1 := append(msg, mac...)
    //fmt.Printf("%x\n", msg)
    
    //get padding string using PKCS #5 to make message a multiple of AES block size (16)
    n := len(mPad1) % 16
    var pStr []byte
    for i := 0; i < (16 - n); i++ {
        pStr = append(pStr, byte(16-n))
    }
    mPad2 := append(mPad1, pStr...)
    
    blockIndex := 0
    var cipherText []byte
    
    //test key
    key := []byte{'\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03'}
    
    //test IV
    iv := [16]byte{'\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03', '\x03'}
    
    //encrypt for every block in plaintext
    for blockIndex < len(mPad2) {
        //initialize new slice to hold current block's XOR
        var xorText []byte
        for i := blockIndex; i < blockIndex + 16; i++ {
            //use IV bits to XOR in first block
            //use previous ciphertext block to XOR for remaining blocks
            if blockIndex == 0 {
                xorText = append(xorText, iv[i] ^ mPad2[i])
            } else {
                xorText = append(xorText, cipherText[i-16] ^ mPad2[i])
            }
        }
        block, err := aes.NewCipher(key) //key should be 16 bytes of input parameter
        if err != nil {
            log.Fatal(err)
        }
        //encrypt XOR'ed block
        cipherBlock := make([]byte, 16)
        block.Encrypt(cipherBlock, xorText)
        
        //append to current ciphertext
        cipherText = append(cipherText, cipherBlock...)
        
        //increment starting index of block
        blockIndex += 16
    }
    fmt.Printf("%x\n", cipherText)
}
func decrypt() {
    
}
func main() {
    if len(os.Args) < 2 {
        log.Fatal("Invalid # of arguments.")
    }
    mode := os.Args[1]
    if mode == "encrypt" {
        encrypt()
    } else if mode == "decrypt" {
        decrypt()
    } else {
        log.Fatal("Invalid mode.")
    }
}



Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.