SoFunction
Updated on 2025-03-05

Golang Usage and Example Explanation

In Go, time packs provide functions to determine and view time. The Sleep() function in Go is used to stop the latest go-routine for at least a specified duration d. A negative sleep time or zero will cause this method to return immediately. In addition, this function is defined under the time package. Here you need to import the "time" package to use these functions.

usage:

func Sleep(d Duration)

Here, d is the sleep time, in seconds.

Return Value: It will pause the latest go-routine for the specified time and then return the output of any operation after sleep is over.

Example 1:

// Golang program to illustrate the usage of 
// Sleep() function 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Calling Sleep method 
    (8 * ) 
  
    // Printed after sleep is over 
    ("Sleep Over.....") 
}

Output:

Sleep Over.....

Here, after running the above code, when the main function is called, the operation is stopped within a given time because the Sleep method is used, and the result is printed.

Example 2:

// Golang program to illustrate the usage of 
// Sleep() function 
  
// Including main package 
package main 
  
// Importing time and fmt 
import ( 
    "fmt"
    "time"
) 
  
// Main function 
func main() { 
  
    // Creating channel using 
    // make keyword 
    mychan1:= make(chan string, 2) 
  
    // Calling Sleep function of go 
    go func() { 
        (2 * ) 
  
        // Displayed after sleep overs 
        mychan1 <- "output1"
    }() 
  
    // Select statement 
    select { 
  
    // Case statement 
    case out:= <-mychan1:
        (out) 
  
    // Calling After method 
    case <-(3 * ):
        ("timeout....1") 
    } 
  
    // Again Creating channel using 
    // make keyword 
    mychan2:= make(chan string, 2) 
  
    // Calling Sleep method of go 
    go func() { 
        (6 * ) 
  
        // Printed after sleep overs 
        mychan2 <- "output2"
    }() 
  
    // Select statement 
    select { 
  
    // Case statement 
    case out:= <-mychan2:
        (out) 
  
    // Calling After method 
    case <-(3 * ):
        ("timeout....2") 
    } 
}

Output:

output1
timeout....2

Here, in the above code "output1", since the duration of the timeout (in After() method) is greater than the sleep time (in Sleep() method), the output is printed before the timeout is displayed, but after this, the following situation occurs that the timeout duration is less than the sleep time, so the timeout is displayed before the printout, so the "timeout....2" will be printed.

This is the end of this article about the usage of Golang () and code examples. For more information about the usage of Golang () please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!