YGNCodeAI နှင့်နည်းပညာအမေးအဖြေ

မှတ်ချက်။ AI ပြောတိုင်းအမှန်မဟုတ်ပါဘူး၊ တခါတလေသူကအမှားတွေပါပြောတက်ပါတယ်။ ကိုယ်ပိုင်စဥ်းစားဆင်ခြင်ဆုံးဖြတ်ပါ။

Pheno Duff 18 Sep 2024, 10:16 am

golang ရဲ့ struct တို့ interface တို့ အကြောင်း အသေးစိတ် ဥပမာများများနဲ့ ရှင်းပြပါ။ နမူနာကုတ်လဲရေးပြပါ။ c programming မှာ golang ရဲ့ struct လို interface လို တူရင်လဲ နမူနာရေးပြပါ။

ဟုတ်ကဲ့ခင်ဗျာ။ Golang ရဲ့ struct နဲ့ interface အကြောင်း ဥပမာတွေနဲ့အတူ ရှင်းပြပေးပါ့မယ်။

  1. Struct: Golang မှာ struct ဆိုတာ custom data type တစ်ခုဖြစ်ပြီး၊ အမျိုးမျိုးသော data type တွေကို စုစည်းထားတဲ့ ပုံစံဖြစ်ပါတယ်။

နမူနာကုဒ်:

type Person struct {
    Name string
    Age  int
}

func main() {
    p1 := Person{Name: "Aung Aung", Age: 25}
    fmt.Println(p1.Name) // Output: Aung Aung
    fmt.Println(p1.Age)  // Output: 25
}
  1. Interface: Interface က method signatures တွေကို စုစည်းထားတဲ့ type တစ်မျိုးဖြစ်ပါတယ်။ ဒါကို polymorphism အတွက် အသုံးပြုပါတယ်။

နမူနာကုဒ်:

type Shape interface {
    Area() float64
}

type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return math.Pi * c.Radius * c.Radius
}

func main() {
    shapes := []Shape{
        Rectangle{Width: 3, Height: 4},
        Circle{Radius: 5},
    }

    for _, shape := range shapes {
        fmt.Printf("Area: %f\n", shape.Area())
    }
}

C programming မှာတော့ Golang ရဲ့ struct နဲ့ interface လို တိကျတဲ့ အရာမရှိပါဘူး။ သို့သော် struct ကတော့ C မှာလည်း ရှိပါတယ်။ Interface အတွက်တော့ function pointers တွေကို သုံးပြီး simulate လုပ်လို့ရပါတယ်။

C မှာ struct နမူနာ:

#include <stdio.h>

struct Person {
    char name[50];
    int age;
};

int main() {
    struct Person p1 = {"Aung Aung", 25};
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);
    return 0;
}

C မှာ interface လို simulate လုပ်တဲ့ နမူနာ:

#include <stdio.h>
#include <math.h>

typedef struct {
    double (*area)(void*);
} Shape;

typedef struct {
    double width;
    double height;
} Rectangle;

double rectangle_area(void* shape) {
    Rectangle* rect = (Rectangle*)shape;
    return rect->width * rect->height;
}

typedef struct {
    double radius;
} Circle;

double circle_area(void* shape) {
    Circle* circle = (Circle*)shape;
    return M_PI * circle->radius * circle->radius;
}

int main() {
    Rectangle rect = {3, 4};
    Circle circle = {5};

    Shape shapes[] = {
        {rectangle_area},
        {circle_area}
    };

    void* data[] = {&rect, &circle};

    for (int i = 0; i < 2; i++) {
        printf("Area: %f\n", shapes[i].area(data[i]));
    }

    return 0;
}

ဒီနမူနာမှာ C က interface လို အလုပ်လုပ်အောင် function pointers တွေကို သုံးထားပါတယ်။ ဒါပေမယ့် Golang ရဲ့ interface လောက်တော့ မလွယ်ကူပါဘူး။

ပြန်လည်မျှဝေပါ... Facebook Twitter LinkedIn WhatsApp Telegram