According to the source from this link : https://gorm.io/docs/index.html
To declaring a model, we do this:
type User struct {
ID uint
Name string
Email *string
Age uint8
Birthday *time.Time
MemberNumber sql.NullString
ActivatedAt sql.NullTime
CreatedAt time.Time
UpdatedAt time.Time
}
Then run migration to create it on the database.
However, I could not find any document mentioning about declaring a model that already exist in database. I suppose there is something like this:
type User struct {
ID uint
Name string
This_struct(User).belongs_to_an_existing_table_named("a_table_name") -- this is an example to explaning what I mean
If and only if we do it by declaring a struct with the same name with an existing table. Can I change the name for simplicity in my code ?
Simply implement the Tabler interface as specified in the docs. Like this:
func (User) TableName() string {
return "a_table_name"
}
Related
I have some problem. In different sites you can find how to correctly describe go struct using swagger(annotations).
Example:
// swagger:model
type User struct {
// the id for this user
//
// required: true
// min: 1
ID int64 `json:"id"`
// the name for this user
// required: true
// min length: 3
Name string `json:"name"`
}
But can someone help me with, how to describe go struct that is in the method and isn't public?
And what I should to enter in #Param field after description for successful generation docs?
Example:
func (n *newStruct) GetPetInfo(c *gin.Context){
info := struct {
PetId uint64 `form:"petId" json:"petId"`
Sl uint64 `form:"sl" json:"sl"`
}{}
...
}
Help me please with this situation)
I am working through the solidity course cryptozombies and heres something im not understanding
struct Zombie {
string name;
uint dna;
uint32 level;
uint32 readyTime;
uint16 winCount;
uint16 lossCount;
}
Zombie[] public zombies;
mapping (uint => address) public zombieToOwner;
mapping (address => uint) ownerZombieCount;
function _createZombie(string memory _name, uint _dna) internal {
uint id = zombies.push(Zombie(_name, _dna, 1, uint32(now + cooldownTime), 0, 0)) - 1;
zombieToOwner[id] = msg.sender;
ownerZombieCount[msg.sender]++;
emit NewZombie(id, _name, _dna);
}
Based on my understanding "zombies" is an array containing a string and different type of integers. If you look in the _createzombie function "id" is set as an uint. How can something of type uint store all these values?
Based on my understanding "zombies" is an array containing a string and different type of integers
This is only partially correct. zombies is in fact an array. But each of its items is of type Zombie.
A struct (docs) is kind of a "wrapper" type - it can contain multiple other datatypes on the inside, but from the outside it's seen as just one datatype (in this case you created a new datatype called Zombie).
You can see it for example in the push() function that accepts one new item of the array - type Zombie (wrapping the other variables).
zombies.push(
Zombie(...) // pushes 1 item of type `Zombie` to the array
)
If I have the data type of something stored in the variable data_type, how can I create a new variable with the data type defined in this variable?
For example:
struct a {
var: String,
}
struct b {
var: String,
}
let var_type = "a";
let variable: var_type { var: "abc" }; // creates struct var_type
As long as you know all of your types at compile time, it is possible to transform unstructured data into typed data based on some value in the data. This is exactly what is done by the popular serde crate
Without knowing the use case, it's difficult to address the question precisely, yet the code below gives two examples about how to accomplish type-mapping using an enum (though match could be used to map any data to any type that is known at compile time).
enum VarType {
A(String),
B(String),
Unknown(String),
}
fn main() {
let _var1 = VarType::A("abc".to_string());
let _var2 = VarType::B("xyz".to_string());
let data = vec![("a", "abc"), ("b", "xyz")];
for item in data {
let (data_type, value) = item;
match data_type {
"a" => VarType::A(value.to_string()),
"b" => VarType::B(value.to_string()),
_ => VarType::Unknown(value.to_string()),
};
}
}
As Isak van Bakel, most said rust is static. However, if you have a list of all the possible structures, you can. (assuming your using serde here!). There is currently
a interesting question discussing polymorphic de-serialisation here, i suggest you take a look as it may help!
You can't. Rust is statically typed.
I'm writing a communication protocol schema for a list of parameters which can be of multiple values: uint64, float64, string or bool.
How can I set a table field to a union of multiple primitive scalar & non-scalar primitive type?
I've already tried using a union of those types, but I end up with the following error when building:
$ schemas/foobar.fbs:28: 0: error: type referenced but not defined
(check namespace): uint64, originally at: schemas/request.fbs:5
Here's the schema in its current state:
namespace Foobar;
enum RequestCode : uint16 { Noop, Get, Set, BulkGet, BulkSet }
union ParameterValue { uint64, float64, bool, string }
table Parameter {
name:string;
value:ParameterValue;
unit:string;
}
table Request {
code:RequestCode = Noop;
payload:[Parameter];
}
table Result {
request:Request;
success:bool = true;
payload:[Parameter];
}
The end result I'm looking for is the Request and Result tables to contain a list of parameters, where a parameter contains a name and value, and optionally the units.
Thx in advance!
Post-answer solution:
Here's what I came up with in the end, thx to Aardappel.
namespace foobar;
enum RequestCode : uint16 { Noop, Get, Set, BulkGet, BulkSet }
union ValueType { UnsignedInteger, SignedInteger, RealNumber, Boolean, Text }
table UnsignedInteger {
value:uint64 = 0;
}
table SignedInteger {
value:int64 = 0;
}
table RealNumber {
value:float64 = 0.0;
}
table Boolean {
value:bool = false;
}
table Text {
value:string (required);
}
table Parameter {
name:string (required);
valueType:ValueType;
unit:string;
}
table Request {
code:RequestCode = Noop;
payload:[Parameter];
}
table Result {
request:Request (required);
success:bool = true;
payload:[Parameter];
}
You currently can't put scalars directly in a union, so you'd have to wrap these in a table or a struct, where struct would likely be the most efficient, e.g.
struct UInt64 { u:uint64 }
union ParameterValue { UInt64, Float64, Bool, string }
This is because a union must be uniformly the same size, so it only allows types to which you can have an offset.
Generally though, FlatBuffers is a strongly typed system, and the schema you are creating here is undoing that by emulating dynamically typed data, since your data is essentially a list of (string, any type) pairs. You may be better off with a system designed for this particular use case, such as FlexBuffers (https://google.github.io/flatbuffers/flexbuffers.html, currently only C++) which explicitly has a map type that is all string -> any type pairs.
Of course, even better is to not store data so generically, but instead make a new schema for each type of request and response you have, and make parameter names into fields, rather than serialized data. This is by far the most efficient, and type safe.
I am getting values from a database table and saving them in their corresponding variable types.
I have a doubt regarding when I get BIT type data from a database(i.e True or False),
what type of datatype should I use to save it in .
E.g
public string Industry { get; set; }
public bool CO2e { get; set; }
public int ID { get; set; }
Here Industry and ID are string and int type respectivly. But the ISEFCO2e is a variable i am using for BIT type of data coming from the table. So using bool with it would be correct?
Yes, that is correct. See here: The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.
Note that a bit may only hold 1 or 0. This is all you need to represent a boolean in a persistent way. Note thay for SQL-server in particular, the database will return "true" and "false", literally.
A bit just has two values which are 0/1 so a bool is the perfect match for such a value.