खोज…


मूल प्रकार रूपांतरण

गो में टाइप रूपांतरण की दो मूल शैलियाँ हैं:

// Simple type conversion
var x := Foo{}    // x is of type Foo
var y := (Bar)Foo // y is of type Bar, unless Foo cannot be cast to Bar, then compile-time error occurs.
// Extended type conversion
var z,ok := x.(Bar)    // z is of type Bar, ok is of type bool - if conversion succeeded, z has the same value as x and ok is true. If it failed, z has the zero value of type Bar, and ok is false.

परीक्षण इंटरफ़ेस कार्यान्वयन

जैसा कि गो निहित इंटरफ़ेस कार्यान्वयन का उपयोग करता है, आपको एक संकलन-समय त्रुटि नहीं मिलेगी यदि आपकी संरचना उस इंटरफ़ेस को लागू नहीं करती है जिसे आपने लागू करने का इरादा किया था। आप प्रकार की कास्टिंग का उपयोग करके स्पष्ट रूप से कार्यान्वयन का परीक्षण कर सकते हैं: MyInterface इंटरफ़ेस {Thing ()} टाइप करें

type MyImplementer struct {}

func (m MyImplementer) Thing() {
    fmt.Println("Huzzah!")
}

// Interface is implemented, no error. Variable name _ causes value to be ignored.
var _ MyInterface = (*MyImplementer)nil

type MyNonImplementer struct {}

// Compile-time error - cannot case because interface is not implemented.
var _ MyInterface = (*MyNonImplementer)nil

प्रकार के साथ एक यूनिट सिस्टम लागू करें

यह उदाहरण बताता है कि कुछ इकाई प्रणाली को लागू करने के लिए गो के प्रकार प्रणाली का उपयोग कैसे किया जा सकता है।

package main

import (
    "fmt"
)

type MetersPerSecond float64
type KilometersPerHour float64

func (mps MetersPerSecond) toKilometersPerHour() KilometersPerHour {
    return KilometersPerHour(mps * 3.6)
}

func (kmh KilometersPerHour) toMetersPerSecond() MetersPerSecond {
    return MetersPerSecond(kmh / 3.6)
}

func main() {
    var mps MetersPerSecond
    mps = 12.5
    kmh := mps.toKilometersPerHour()
    mps2 := kmh.toMetersPerSecond()
    fmt.Printf("%vmps = %vkmh = %vmps\n", mps, kmh, mps2)
}

खेल के मैदान में खोलें



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow