SyMind / learning

路漫漫其修远兮,吾将上下而求索。
9 stars 1 forks source link

Go 语言中的 Import #45

Open SyMind opened 1 year ago

SyMind commented 1 year ago

1. Direct import

// Golang program to demonstrate the 
// application of direct import
package main

import "fmt"

// Main function
func main() {
    fmt.Println("Hello Geeks")
}

2. Grouped import

// A program to demonstrate the
// application of grouped import
package main

import (
    "fmt"
    "math"
)

// Main function
func main() {

    // math.Exp2(5) returns 
    // the value of 2^5, wiz 32
    c := math.Exp2(5)

    // Println is a function in fmt package 
    // which prints value of c in a new
    // line on console
    fmt.Println(c)
}

3. Nested import

// Golang Program to demonstrate
// application of nested import
package main

 import (
    "fmt"
    "math/rand"
)

func main() {
    // this generates & displays a
    // random integer value < 100
    fmt.Println(rand.Int(100))
}

4. Aliased import

// Golang Program to demonstrate
// the application of aliased import
package main

import (
    f "fmt"
    m "math"
)

// Main function
func main() {

    // this assigns value
    // of 2^5 = 32 to var c
    c := m.Exp2(5)  

    // this prints the
    // value stored in var c
    f.Println(c)                
}

5. Dot import

// Golang Program to demonstrate
// the application of dot import
package main

import (
    "fmt"
    . "math"
)

func main() {

    // this prints the value of
    // 2^5 = 32 on the console
    fmt.Println(Exp2(5))    
}

6. Blank import

// PROGRAM1
package main
// Program to demonstrate importance of blank import

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println("Hello Geeks")
}

// -------------------------------------------------------------------------------------
// Program1 looks accurate and everything
// seems right but the compiler will throw an
// error upon building this code. Why? Because
// we imported the math/rand package but
// We didn't use it anywhere in the program.
// That's why. The following code is a solution.
//-------------------------------------------------------------------------------------

// PROGRAM2
package main
// Program to demonstrate application of blank import

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

func main() {
    fmt.Println("Hello Geeks")
    // This program compiles successfully and
    // simply prints Hello Geeks on the console.
}

7. Relative import

package main

import "github.com/gopherguides/greet"

// Main function
func main() {
    // The hello function is in
    // the mentioned directory
    greet.Hello()
    // This function simply prints
    // hello world on the console screen
}