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

go 구조체와 메서드 연결

package main

import "fmt"


type Person struct{
    name string
    age int
}
func(p *Person) greeting(){
    fmt.Println("Hello~")
}
func (p *Student) greeting(){
    fmt.Println("Hello~ Student")
}

type Student struct{
    Person
    school string
    grade int
}

func main(){
    var s Student
    s.Person.greeting()
    s.greeting()
    
}

go 구조체와 포인터변수

package main

import "fmt"

type Rectangle struct {
    width, height int
}

func rectangleScalaA(rect *Rectangle, factor int){
    rect.width = rect.width * factor
    rect.height = rect.height * factor
}


func rectangleScalaB(rect Rectangle, factor int){
    rect.width = rect.width * factor
    rect.height = rect.height * factor
}

func main() {
    rect1 := Rectangle{30, 30}
    rectangleScalaA(&rect1, 10)
    fmt.Println(rect1) //주소를 넘겨주기 때문에 바뀐 값이 들어감
    
    rect2 := Rectangle{30, 30}
    rectangleScalaB(rect2, 10)
    fmt.Println(rect2) //값을 넘겨주기 때문에 rect2는 변하지 않음.
}

/*
    포인터 변수는
    pointerVar = &{} 형태
    그래서 &pointerVar은 주소를 나타내고
    *pointerVar는 주소의 값을 나타낸다.
*/

go 맵을 매개변수로 받고 맵을 리턴하는 함수

package main

import "fmt"

func main() {

    var newMap = map[string]string{
        "one" : "1",
        "two" : "2",
        "three" : "3",
    }

    fmt.Println(mapTest(newMap, "two"))
    
}

func mapTest(map1 map[string]string, key1 string) (returnMap map[string]string){
    //returnMap 선언된 상태
    //할당을 해야 함
    //할당은 = 이것으로
    returnMap = make(map[string]string)
    //or returnMap = map[string]string{}
    
    Loop : 
        for key, value := range map1 {
            if key==key1 {
                returnMap[key] = value
                break Loop
            }
        }
    return            
    
        
}

Golang Bot

package main

import (
	"fmt"
	"os"
	"bufio"
	"strings"
	"time"
	"math/rand"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Enter a move (rock, lizard, paper, spock, scissors):")
	move, _ := reader.ReadString('\n')

	// Trim string
	move = strings.TrimSpace(move)

	// Have the bot make the moves
	possibleMoves := []string{"rock", "lizard", "paper", "spock", "scissors"}

	// Generate random num
	rand.Seed(time.Now().UTC().UnixNano())
	botMove := possibleMoves[randInt(0, len(possibleMoves) - 1)]

	fmt.Println("The bot guessed", botMove)

	// Calculate outcome
	switch move {
	case "rock":
		if botMove == "scissors" || botMove == "lizard" {
			win()
		} else {
			lose()
		}
	case "lizard":
		if botMove == "spock" || botMove == "paper" {
			win()
		} else {
			lose()
		}
	case "paper":
		if botMove == "rock" || botMove == "spock" {
			win()
		} else {
			lose()
		}
	case "spock":
		if botMove == "scissors" || botMove == "rock" {
			win()
		} else {
			lose()
		}
	case "scissors":
		if botMove == "paper" || botMove == "lizard" {
			win()
		} else {
			lose()
		}
	}
}

func win() {
	fmt.Println("Congratulations, you won!")
}

func lose() {
	fmt.Println("You lost! Too bad.")
}

func randInt(min int, max int) int {
    return min + rand.Intn(max-min)
}

happyday

package main

import (
	"fmt"
	"time"
)

func Happy() {
    fmt.Print("\n.~~~~.\ni====i_\n|cccc|_)\n|cccc|\n`-==-'\nHappy Programmer’s day!")
}

func Work(){
    fmt.Println("go to work")
}

func main() {
	if time.Now().YearDay() == 1 << 8{
	   Happy()
	}else{
	   Work()
	}
}

Execute GO Language Online

package main

import ("fmt"
    "math/rand"
)

const NUMS = 100
var num [NUMS] int

func gen_nums() {
    rand.Seed(183)
    for count := 0; count < NUMS; count++ {
        num[count] = rand.Intn(10000)
    }
}

func swap(x *int, y *int) {
    temp := *x
    *x = *y
    *y = temp
}

func main() {
    gen_nums()
    for count1 := 0; count1 < NUMS - 1; count1++ {
        for count2 := count1 + 1; count2 < NUMS; count2++ {
            if num[count1] > num[count2] {
                swap(&num[count1], &num[count2])
            }
        }
    }
    
    for count := 0; count < NUMS; count++ {
        fmt.Printf("%d\n", num[count])
    }
}

qdqwdqw

package main

import "fmt"

type A interface {
    A()
}
type B interface {
    A
    B()
}

type AA struct {}
type BB struct {}

func (aa *AA) A() {
    fmt.Println("AA method A()")
}


func (bb *BB) A() {
    fmt.Println("BB method A()")
}


func (bb *BB) B() {
    fmt.Println("BB method B()")
}

func Factory(c *A) (d *A) {
    return d, nil
}

func main() {
    aa := &AA{}
    aa.A()
   fmt.Printf("hello, world\n")
}

testgo

package main

import "fmt"

func main() {
   fmt.Printf("hello, world\n")
   fmt.Printf("haha")
}

Execute GO Language Online

package main

import "fmt"

func main() {
   fmt.Printf("hello, world\n")
}

new Go lang

//Go language
//Starting with the main package
package main
import 

int main() 

{
 e := echo.New()
 // here goes the Middleware

 e.Use(middleware.Logger())
 e.Use(middleware.Recover())

 //CORS
 e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  AllowOrigins: []string{"*"},
  AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH, echo.POST, echo.DELETE},
 }))


// Server for middle wave
 e.Run(standard.New(":1323"))
}


// imported packages in server,go
// middleware in the application
// Middleware
//server log
 e.Use(middleware.Logger())
//reover in the chain
 e.Use(middleware.Recover())
//webservers cross domain access controls
 e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
  AllowOrigins: []string{"*"},
  AllowMethods: []string{echo.GET, echo.HEAD, echo.PUT, echo.PATCH,    echo.POST, echo.DELETE},
 }))
//webserver for echo on 1323 port
e.Run(standard.New(":1323"))

// Route for handler 

 e.GET("/", func(c echo.Context) error {       return c.String(http.StatusOK, "Hello, World!\n")  
})

//controlers
e.POST("/users", controllers.CreateUser)

// Main Server
 e.Run(standard.New(":1323"))
}


Previous 1 ... 3 4 5 6 7 8 9 ... 17 Next
Advertisements
Loading...

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