Model Data
Struct, pemetaan tipe, dan pembuatan model.
Generator binding Wails v3 secara otomatis mendeteksi tipe konstanta Go dan menghasilkan enum TypeScript atau const object JavaScript. Tanpa registrasi, tanpa konfigurasi — cukup definisikan tipe dan konstanta di Go, dan generator menangani sisanya.
Definisikan tipe bernama dengan konstanta di Go:
type Status string
const ( StatusActive Status = "active" StatusPending Status = "pending" StatusClosed Status = "closed")Gunakan tipe tersebut dalam struct atau metode service:
type Ticket struct { ID int `json:"id"` Title string `json:"title"` Status Status `json:"status"`}Hasilkan binding:
wails3 generate bindingsOutput generator akan melaporkan jumlah enum bersama model:
3 Enums, 5 ModelsGunakan di frontend:
import { Ticket, Status } from './bindings/changeme/models'
const ticket = new Ticket({ id: 1, title: "Bug report", status: Status.StatusActive})Itu saja! Tipe enum ditegakkan di Go dan JavaScript/TypeScript.
Enum di Wails adalah tipe bernama dengan tipe dasar primitif, dikombinasikan dengan deklarasi const dari tipe tersebut.
// Title is a titletype Title string
const ( // Mister is a title Mister Title = "Mr" Miss Title = "Miss" Ms Title = "Ms" Mrs Title = "Mrs" Dr Title = "Dr")TypeScript yang Dihasilkan:
/** * Title is a title */export enum Title { /** * The Go zero value for the underlying type of the enum. */ $zero = "",
/** * Mister is a title */ Mister = "Mr", Miss = "Miss", Ms = "Ms", Mrs = "Mrs", Dr = "Dr",}JavaScript yang Dihasilkan:
/** * Title is a title * @readonly * @enum {string} */export const Title = { /** * The Go zero value for the underlying type of the enum. */ $zero: "",
/** * Mister is a title */ Mister: "Mr", Miss: "Miss", Ms: "Ms", Mrs: "Mrs", Dr: "Dr",};type Priority int
const ( PriorityLow Priority = 0 PriorityMedium Priority = 1 PriorityHigh Priority = 2)TypeScript yang Dihasilkan:
export enum Priority { /** * The Go zero value for the underlying type of the enum. */ $zero = 0,
PriorityLow = 0, PriorityMedium = 1, PriorityHigh = 2,}Type alias Go (=) juga berfungsi, tetapi menghasilkan output sedikit berbeda — definisi tipe plus const object, alih-alih enum TypeScript native:
// Age is an integer with some predefined valuestype Age = int
const ( NewBorn Age = 0 Teenager Age = 12 YoungAdult Age = 18
// Oh no, some grey hair! MiddleAged Age = 50 Mathusalem Age = 1000 // Unbelievable!)TypeScript yang Dihasilkan:
/** * Age is an integer with some predefined values */export type Age = number;
/** * Predefined constants for type Age. * @namespace */export const Age = { NewBorn: 0, Teenager: 12, YoungAdult: 18,
/** * Oh no, some grey hair! */ MiddleAged: 50,
/** * Unbelievable! */ Mathusalem: 1000,};JavaScript yang Dihasilkan:
/** * Age is an integer with some predefined values * @typedef {number} Age */
/** * Predefined constants for type Age. * @namespace */export const Age = { NewBorn: 0, Teenager: 12, YoungAdult: 18,
/** * Oh no, some grey hair! */ MiddleAged: 50,
/** * Unbelievable! */ Mathusalem: 1000,};$zeroSetiap enum tipe bernama menyertakan anggota khusus $zero yang mewakili nilai nol Go untuk tipe dasarnya:
| Tipe Dasar | Nilai $zero |
|---|---|
string | "" |
int, int8, int16, int32, int64 | 0 |
uint, uint8, uint16, uint32, uint64 | 0 |
float32, float64 | 0 |
bool | false |
Saat field struct menggunakan tipe enum dan tidak ada nilai yang diberikan, constructor default ke $zero:
export class Person { "Title": Title;
constructor($$source: Partial<Person> = {}) { if (!("Title" in $$source)) { this["Title"] = Title.$zero; // defaults to "" } Object.assign(this, $$source); }}Ini memastikan inisialisasi type-safe saat menghasilkan class — field enum tidak pernah undefined. Saat menghasilkan interface TypeScript (menggunakan -i), tidak ada constructor dan field dapat tidak ada seperti biasa.
Saat field struct memiliki tipe enum, kode yang dihasilkan mempertahankan tipe tersebut alih-alih fallback ke primitif:
type Person struct { Title Title Name string Age Age}TypeScript yang Dihasilkan:
export class Person { "Title": Title; "Name": string; "Age": Age;
constructor($$source: Partial<Person> = {}) { if (!("Title" in $$source)) { this["Title"] = Title.$zero; } if (!("Name" in $$source)) { this["Name"] = ""; } if (!("Age" in $$source)) { this["Age"] = 0; }
Object.assign(this, $$source); }}Field Title bertipe Title, bukan string. Ini memberikan IDE Anda autocompletion dan type checking penuh pada nilai enum.
Enum yang didefinisikan di paket terpisah sepenuhnya didukung. Enum dihasilkan ke direktori paket yang sesuai:
package services
type Title string
const ( Mister Title = "Mr" Miss Title = "Miss" Ms Title = "Ms")package main
import "myapp/services"
func (*GreetService) Greet(name string, title services.Title) string { return "Hello " + string(title) + " " + name}Enum Title dihasilkan di file model services, dan path import diselesaikan secara otomatis:
export enum Title { $zero = "", Mister = "Mr", Miss = "Miss", Ms = "Ms",}Anda dapat menambahkan metode ke tipe enum di Go. Ini tidak memengaruhi pembuatan binding tetapi memberikan fungsionalitas server-side yang berguna:
type Title string
func (t Title) String() string { return string(t)}
const ( Mister Title = "Mr" Miss Title = "Miss")Enum yang dihasilkan identik apakah metode Go ada pada tipe atau tidak.
Generator mempertahankan komentar Go sebagai JSDoc dalam output yang dihasilkan:
Artinya IDE Anda akan menampilkan dokumentasi untuk nilai enum saat hover.
Generator binding mendukung enum dengan tipe dasar Go berikut:
| Tipe Go | Berfungsi sebagai Enum |
|---|---|
string | Ya |
int, int8, int16, int32, int64 | Ya |
uint, uint8, uint16, uint32, uint64 | Ya |
float32, float64 | Ya |
byte (uint8) | Ya |
rune (int32) | Ya |
bool | Ya |
complex64, complex128 | Tidak |
Berikut tidak didukung untuk pembuatan enum:
json.Marshaler atau encoding.TextMarshaler kustom — Serialisasi kustom berarti nilai yang dihasilkan mungkin tidak cocok dengan perilaku runtime, sehingga generator melewatkannyaiota standar berfungsi dengan baik karena compiler menyelesaikannya ke nilai konkretcomplex64 dan complex128 tidak dapat menjadi tipe dasar enumGo:
package main
import ( "github.com/wailsapp/wails/v3/pkg/application")
// BackgroundType defines the type of backgroundtype BackgroundType string
const ( BackgroundSolid BackgroundType = "solid" BackgroundGradient BackgroundType = "gradient" BackgroundImage BackgroundType = "image")
type BackgroundConfig struct { Type BackgroundType `json:"type"` Value string `json:"value"`}
type ThemeService struct{}
func (*ThemeService) GetBackground() BackgroundConfig { return BackgroundConfig{ Type: BackgroundSolid, Value: "#ffffff", }}
func (*ThemeService) SetBackground(config BackgroundConfig) error { // Apply background return nil}
func main() { app := application.New(application.Options{ Services: []application.Service{ application.NewService(&ThemeService{}), }, }) app.Window.New() app.Run()}Frontend (TypeScript):
import { GetBackground, SetBackground } from './bindings/changeme/themeservice'import { BackgroundConfig, BackgroundType } from './bindings/changeme/models'
// Get current backgroundconst bg = await GetBackground()
// Check the type using enum valuesif (bg.type === BackgroundType.BackgroundSolid) { console.log("Solid background:", bg.value)}
// Set a new backgroundawait SetBackground(new BackgroundConfig({ type: BackgroundType.BackgroundGradient, value: "linear-gradient(to right, #000, #fff)"}))Frontend (JavaScript):
import { GetBackground, SetBackground } from './bindings/changeme/themeservice'import { BackgroundConfig, BackgroundType } from './bindings/changeme/models'
// Use enum values for type-safe comparisonsconst bg = await GetBackground()
switch (bg.type) { case BackgroundType.BackgroundSolid: applySolid(bg.value) break case BackgroundType.BackgroundGradient: applyGradient(bg.value) break case BackgroundType.BackgroundImage: applyImage(bg.value) break}Model Data
Struct, pemetaan tipe, dan pembuatan model.
Binding Metode
Bind metode Go ke frontend.
Binding Lanjutan
Directive, injeksi kode, dan ID kustom.
Praktik Terbaik
Pola desain binding.
Ada pertanyaan? Tanyakan di Discord atau lihat contoh binding.