Z
Z
Zuoya2020-10-01 14:40:37
C++ / C#
Zuoya, 2020-10-01 14:40:37

How to do "trait Rust" in C?

Good day! I study programming and languages ​​C, Rust. How can you do something like trait from Rust in C?
Here is an example code

void say_colour(char *s);
void say_colour(char *s){  printf("машина цветом %s",s);}
typedef struct {
    char z[10];
    void(*say_colour)(char *s);
}Blue;

typedef struct{
    void *colour;
}Car;

int main(int argc, char const *argv[]){
    Blue b = {.z ="blue",.say_colour=say_colour};
    Car car = {.colour = &b};
    //b.say_colour(b.z);
    car.colour.say_colour();
    
    return 0;
}

In Rust, I would make color a type of trait . which implemented the structures I needed. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cython, 2020-10-01
@cython

This can be done by converting a pointer to an existing structure into a trait structure that describes the desired properties. But with this approach, if the trait does not match, there will be a Segmentation Fault

#include <stdio.h>

void say_colour(char *s);
void say_colour(char *s){  printf("машина цветом %s",s);}

typedef struct { // Трейт
  char z[10];
  void(*say_colour)(char* s);
} Colour;

typedef struct {
    char z[10];
    void(*say_colour)(char *s);
    int a; // Доп свойство
} Blue;

typedef struct{
    Colour* colour;
} Car;

int main(int argc, char const *argv[]){
    Blue b = {.z ="blue",.say_colour=say_colour};
    Car car = {
    	.colour = (Colour*)&b // Преобразуем Blue в Colour
    };
    car.colour->say_colour("dsfd");
    
    return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question