"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Python에서 Pydantic을 사용하는 모범 사례

Python에서 Pydantic을 사용하는 모범 사례

2024-08-06에 게시됨
검색:927

Best Practices for Using Pydantic in Python

Pydantic is a Python library that simplifies data validation using type hints. It ensures data integrity and offers an easy way to create data models with automatic type checking and validation.

In software applications, reliable data validation is crucial to prevent errors, security issues, and unpredictable behavior.

This guide provides best practices for using Pydantic in Python projects, covering model definition, data validation, error handling, and performance optimization.


Installing Pydantic

To install Pydantic, use pip, the Python package installer, with the command:

pip install pydantic

This command installs Pydantic and its dependencies.

Basic Usage

Create Pydantic models by making classes that inherit from BaseModel. Use Python type annotations to specify each field's type:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

Pydantic supports various field types, including int, str, float, bool, list, and dict. You can also define nested models and custom types:

from typing import List, Optional
from pydantic import BaseModel

class Address(BaseModel):
    street: str
    city: str
    zip_code: Optional[str] = None

class User(BaseModel):
    id: int
    name: str
    email: str
    age: Optional[int] = None
    addresses: List[Address]

Once you've defined a Pydantic model, create instances by providing the required data. Pydantic will validate the data and raise errors if any field doesn't meet the specified requirements:

user = User(
    id=1,
    name="John Doe",
    email="[email protected]",
    addresses=[{"street": "123 Main St", "city": "Anytown", "zip_code": "12345"}]
)

print(user)

# Output:
# id=1 name='John Doe' email='[email protected]' age=None addresses=[Address(street='123 Main St', city='Anytown', zip_code='12345')]

Defining Pydantic Models

Pydantic models use Python type annotations to define data field types.

They support various built-in types, including:

  • Primitive types: str, int, float, bool
  • Collection types: list, tuple, set, dict
  • Optional types: Optional from the typing module for fields that can be None
  • Union types: Union from the typing module to specify a field can be one of several types

Example:

from typing import List, Dict, Optional, Union
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    tags: List[str]
    metadata: Dict[str, Union[str, int, float]]

class Order(BaseModel):
    order_id: int
    items: List[Item]
    discount: Optional[float] = None

Custom Types

In addition to built-in types, you can define custom types using Pydantic's conint, constr, and other constraint functions.

These allow you to add additional validation rules, such as length constraints on strings or value ranges for integers.

Example:

from pydantic import BaseModel, conint, constr

class Product(BaseModel):
    name: constr(min_length=2, max_length=50)
    quantity: conint(gt=0, le=1000)
    price: float

product = Product(name="Laptop", quantity=5, price=999.99)

Required vs. Optional Fields

By default, fields in a Pydantic model are required unless explicitly marked as optional.

If a required field is missing during model instantiation, Pydantic will raise a ValidationError.

Example:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

user = User(id=1, name="John Doe")


# Output
#  Field required [type=missing, input_value={'id': 1, 'name': 'John Doe'}, input_type=dict]

Optional Fields with Default Values

Fields can be made optional by using Optional from the typing module and providing a default value.

Example:

from pydantic import BaseModel
from typing import Optional

class User(BaseModel):
    id: int
    name: str
    email: Optional[str] = None

user = User(id=1, name="John Doe")

In this example, email is optional and defaults to None if not provided.

Nested Models

Pydantic allows models to be nested within each other, enabling complex data structures.

Nested models are defined as fields of other models, ensuring data integrity and validation at multiple levels.

Example:

from pydantic import BaseModel
from typing import Optional, List


class Address(BaseModel):
    street: str
    city: str
    zip_code: Optional[str] = None

class User(BaseModel):
    id: int
    name: str
    email: str
    addresses: List[Address]

user = User(
    id=1,
    name="John Doe",
    email="[email protected]",
    addresses=[{"street": "123 Main St", "city": "Anytown"}]
)

Best Practices for Managing Nested Data

When working with nested models, it's important to:

  • Validate data at each level: Ensure each nested model has its own validation rules and constraints.
  • Use clear and consistent naming conventions: This makes the structure of your data more readable and maintainable.
  • Keep models simple: Avoid overly complex nested structures. If a model becomes too complex, consider breaking it down into smaller, more manageable components.

Data Validation

Pydantic includes a set of built-in validators that handle common data validation tasks automatically.

These validators include:

  • Type validation: Ensures fields match the specified type annotations (e.g., int, str, list).
  • Range validation: Enforces value ranges and lengths using constraints like conint, constr, confloat.
  • Format validation: Checks specific formats, such as EmailStr for validating email addresses.
  • Collection validation: Ensures elements within collections (e.g., list, dict) conform to specified types and constraints.

These validators simplify the process of ensuring data integrity and conformity within your models.

Here are some examples demonstrating built-in validators:

from pydantic import BaseModel, EmailStr, conint, constr

class User(BaseModel):
    id: conint(gt=0)  # id must be greater than 0
    name: constr(min_length=2, max_length=50)  # name must be between 2 and 50 characters
    email: EmailStr  # email must be a valid email address
    age: conint(ge=18)  # age must be 18 or older

user = User(id=1, name="John Doe", email="[email protected]", age=25)

In this example, the User model uses built-in validators to ensure the id is greater than 0, the name is between 2 and 50 characters, the email is a valid email address, and the age is 18 or older.
To be able to use the email validator, you need to install an extension to pydantic:

pip install pydantic[email]

Custom Validators

Pydantic allows you to define custom validators for more complex validation logic.

Custom validators are defined using the @field_validator decorator within your model class.

Example of a custom validator:

from pydantic import BaseModel, field_validator


class Product(BaseModel):
    name: str
    price: float

    @field_validator('price')
    def price_must_be_positive(cls, value):
        if value 



Here, the price_must_be_positive validator ensures that the price field is a positive number.

Custom validators are registered automatically when you define them within a model using the @field_validator decorator. Validators can be applied to individual fields or across multiple fields.

Example of registering a validator for multiple fields:

from pydantic import BaseModel, field_validator


class Person(BaseModel):
    first_name: str
    last_name: str

    @field_validator('first_name', 'last_name')
    def names_cannot_be_empty(cls, value):
        if not value:
            raise ValueError('Name fields cannot be empty')
        return value

person = Person(first_name="John", last_name="Doe")

In this example, the names_cannot_be_empty validator ensures that both the first_name and last_name fields are not empty.

Using Config Classes

Pydantic models can be customized using an inner Config class.

This class allows you to set various configuration options that affect the model's behavior, such as validation rules, JSON serialization, and more.

Example of a Config class:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

    class Config:
        str_strip_whitespace = True  # Strip whitespace from strings
        str_min_length = 1  # Minimum length for any string field

user = User(id=1, name="  John Doe  ", email="[email protected]")

print(user)

# Output:
# id=1 name='John Doe' email='[email protected]'

In this example, the Config class is used to strip whitespace from string fields and enforce a minimum length of 1 for any string field.

Some common configuration options in Pydantic's Config class include:

  • str_strip_whitespace: Automatically strip leading and trailing whitespace from string fields.
  • str_min_length: Set a minimum length for any string field.
  • validate_default: Validate all fields, even those with default values.
  • validate_assignment: Enable validation on assignment to model attributes.
  • use_enum_values: Use the values of enums directly instead of the enum instances.
  • json_encoders: Define custom JSON encoders for specific types.

Error Handling

When Pydantic finds data that doesn't conform to the model's schema, it raises a ValidationError.

This error provides detailed information about the issue, including the field name, the incorrect value, and a description of the problem.

Here's an example of how default error messages are structured:

from pydantic import BaseModel, ValidationError, EmailStr

class User(BaseModel):
    id: int
    name: str
    email: EmailStr

try:
    user = User(id='one', name='John Doe', email='invalid-email')
except ValidationError as e:
    print(e.json())

# Output:
# [{"type":"int_parsing","loc":["id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"one","url":"https://errors.pydantic.dev/2.8/v/int_parsing"},{"type":"value_error","loc":["email"],"msg":"value is not a valid email address: An email address must have an @-sign.","input":"invalid-email","ctx":{"reason":"An email address must have an @-sign."},"url":"https://errors.pydantic.dev/2.8/v/value_error"}]

In this example, the error message will indicate that id must be an integer and email must be a valid email address.

Customizing Error Messages

Pydantic allows you to customize error messages for specific fields by raising exceptions with custom messages in validators or by setting custom configurations.

Here’s an example of customizing error messages:

from pydantic import BaseModel, ValidationError, field_validator

class Product(BaseModel):
    name: str
    price: float

    @field_validator('price')
    def price_must_be_positive(cls, value):
        if value 



In this example, the error message for price is customized to indicate that it must be a positive number.

Best Practices for Error Reporting

Effective error reporting involves providing clear, concise, and actionable feedback to users or developers.

Here are some best practices:

  • Log errors: Use logging mechanisms to record validation errors for debugging and monitoring purposes.
  • Return user-friendly messages: When exposing errors to end-users, avoid technical jargon. Instead, provide clear instructions on how to correct the data.
  • Aggregate errors: When multiple fields are invalid, aggregate the errors into a single response to help users correct all issues at once.
  • Use consistent formats: Ensure that error messages follow a consistent format across the application for easier processing and understanding.

Examples of best practices in error reporting:

from pydantic import BaseModel, ValidationError, EmailStr
import logging

logging.basicConfig(level=logging.INFO)

class User(BaseModel):
    id: int
    name: str
    email: EmailStr

def create_user(data):
    try:
        user = User(**data)
        return user
    except ValidationError as e:
        logging.error("Validation error: %s", e.json())
        return {"error": "Invalid data provided", "details": e.errors()}

user_data = {'id': 'one', 'name': 'John Doe', 'email': 'invalid-email'}
response = create_user(user_data)
print(response)

# Output:
# ERROR:root:Validation error: [{"type":"int_parsing","loc":["id"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"one","url":"https://errors.pydantic.dev/2.8/v/int_parsing"},{"type":"value_error","loc":["email"],"msg":"value is not a valid email address: An email address must have an @-sign.","input":"invalid-email","ctx":{"reason":"An email address must have an @-sign."},"url":"https://errors.pydantic.dev/2.8/v/value_error"}]
# {'error': 'Invalid data provided', 'details': [{'type': 'int_parsing', 'loc': ('id',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'one', 'url': 'https://errors.pydantic.dev/2.8/v/int_parsing'}, {'type': 'value_error', 'loc': ('email',), 'msg': 'value is not a valid email address: An email address must have an @-sign.', 'input': 'invalid-email', 'ctx': {'reason': 'An email address must have an @-sign.'}}]}

In this example, validation errors are logged, and a user-friendly error message is returned, helping maintain application stability and providing useful feedback to the user.


Performance Considerations

Lazy initialization is a technique that postpones the creation of an object until it is needed.

In Pydantic, this can be useful for models with fields that are costly to compute or fetch. By delaying the initialization of these fields, you can reduce the initial load time and improve performance.

Example of lazy initialization:

from pydantic import BaseModel
from functools import lru_cache

class DataModel(BaseModel):
    name: str
    expensive_computation: str = None

    @property
    @lru_cache(maxsize=1)
    def expensive_computation(self):
        # Simulate an expensive computation
        result = "Computed Value"
        return result

data_model = DataModel(name="Test")
print(data_model.expensive_computation)

In this example, the expensive_computation field is computed only when accessed for the first time, reducing unnecessary computations during model initialization.

Redundant Validation

Pydantic models automatically validate data during initialization.

However, if you know that certain data has already been validated or if validation is not necessary in some contexts, you can disable validation to improve performance.

This can be done using the model_construct method, which bypasses validation:

Example of avoiding redundant validation:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

# Constructing a User instance without validation
data = {'id': 1, 'name': 'John Doe', 'email': '[email protected]'}
user = User.model_construct(**data)

In this example, User.model_construct is used to create a User instance without triggering validation, which can be useful in performance-critical sections of your code.

Efficient Data Parsing

When dealing with large datasets or high-throughput systems, efficiently parsing raw data becomes critical.

Pydantic provides the model_validate_json method, which can be used to parse JSON or other serialized data formats directly into Pydantic models.

Example of efficient data parsing:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

json_data = '{"id": 1, "name": "John Doe", "email": "[email protected]"}'
user = User.model_validate_json(json_data)
print(user)

In this example, model_validate_json is used to parse JSON data into a User model directly, providing a more efficient way to handle serialized data.

Controlling Validation

Pydantic models can be configured to validate data only when necessary.

The validate_default and validate_assignment options in the Config class control when validation occurs, which can help improve performance:

  • validate_default: When set to False, only fields that are set during initialization are validated.
  • validate_assignment: When set to True, validation is performed on field assignment after the model is created.

Example configuration:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

    class Config:
        validate_default = False  # Only validate fields set during initialization
        validate_assignment = True  # Validate fields on assignment

user = User(id=1, name="John Doe", email="[email protected]")
user.email = "[email protected]"  # This assignment will trigger validation

In this example, validate_default is set to False to avoid unnecessary validation during initialization, and validate_assignment is set to True to ensure that fields are validated when they are updated.


Settings Management

Pydantic's BaseSettings class is designed for managing application settings, supporting environment variable loading and type validation.

This helps in configuring applications for different environments (e.g., development, testing, production).

Consider this .env file:

database_url=db
secret_key=sk
debug=False

Example of using BaseSettings:

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    secret_key: str
    debug: bool = False

    class Config:
        env_file = ".env"

settings = Settings()
print(settings.model_dump())

# Output:
# {'database_url': 'db', 'secret_key': 'sk', 'debug': False}

In this example, settings are loaded from environment variables, and the Config class specifies that variables can be loaded from a .env file.

For using BaseSettings you will need to install an additional package:

pip install pydantic-settings

Managing settings effectively involves a few best practices:

  • Use environment variables: Store configuration values in environment variables to keep sensitive data out of your codebase.
  • Provide defaults: Define sensible default values for configuration settings to ensure the application runs with minimal configuration.
  • Separate environments: Use different configuration files or environment variables for different environments (e.g., .env.development, .env.production).
  • Validate settings: Use Pydantic's validation features to ensure all settings are correctly typed and within acceptable ranges.

Common Pitfalls and How to Avoid Them

One common mistake when using Pydantic is misapplying type annotations, which can lead to validation errors or unexpected behavior.

Here are a few typical mistakes and their solutions:

  • Misusing Union Types: Using Union incorrectly can complicate type validation and handling.
  • Optional Fields without Default Values: Forgetting to provide a default value for optional fields can lead to None values causing errors in your application.
  • Incorrect Type Annotations: Assigning incorrect types to fields can cause validation to fail. For example, using str for a field that should be an int.

Ignoring Performance Implications

Ignoring performance implications when using Pydantic can lead to slow applications, especially when dealing with large datasets or frequent model instantiations.

Here are some strategies to avoid performance bottlenecks:

  • Leverage Configuration Options: Use Pydantic's configuration options like validate_default and validate_assignment to control when validation occurs.
  • Optimize Nested Models: When working with nested models, ensure that you are not over-validating or duplicating validation logic.
  • Use Efficient Parsing Methods: Utilize model_validate_json and model_validate for efficient data parsing.
  • Avoid Unnecessary Validation: Use the model_construct method to create models without validation when the data is already known to be valid.

Overcomplicating Models

Overcomplicating Pydantic models can make them difficult to maintain and understand.

Here are some tips to keep models simple and maintainable:

  • Document Your Models: Use docstrings and comments to explain complex validation rules or business logic embedded in models.
  • Encapsulate Logic Appropriately: Keep validation and business logic within appropriate model methods or external utilities to avoid cluttering model definitions.
  • Use Inheritance Sparingly: While inheritance can promote code reuse, excessive use can make the model hierarchy complex and harder to follow.
  • Avoid Excessive Nesting: Deeply nested models can be hard to manage. Aim for a balanced level of nesting.

Conclusion

In this guide, we have covered various best practices for using Pydantic effectively in your Python projects.

We began with the basics of getting started with Pydantic, including installation, basic usage, and defining models. We then delved into advanced features like custom types, serialization and deserialization, and settings management.

Key performance considerations, such as optimizing model initialization and efficient data parsing, were highlighted to ensure your applications run smoothly.

We also discussed common pitfalls, such as misusing type annotations, ignoring performance implications, and overcomplicating models, and provided strategies to avoid them.

Applying these best practices in your real-world projects will help you leverage the full power of Pydantic, making your code more robust, maintainable, and performant.

릴리스 선언문 이 기사는 https://dev.to/devasservice/best-practices-for-using-pydantic-in-python-2021?1에서 복제됩니다.1 침해 내용이 있는 경우, [email protected]에 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>
  • Golang에서 Google 드라이브 다운로더 구축(1부)
    Golang에서 Google 드라이브 다운로더 구축(1부)
    소개 이 튜토리얼에서는 Google 드라이브 및 기타 클라우드 제공업체에서 파일을 다운로드할 수 있는 강력한 다운로더를 구축하겠습니다. Golang의 효율적인 동시성 패턴을 사용하면 여러 다운로드를 동시에 관리하고, 대용량 파일을 스트리밍하고, 진행 상...
    프로그램 작성 2024-11-08에 게시됨
  • 4에서 PHP의 신속한 배포
    4에서 PHP의 신속한 배포
    Servbay는 개발 환경을 효율적으로 구성하기 위한 최고의 도구로 부상했습니다. 이 가이드에서는 PHP 8.1을 빠르고 안전하게 배포하는 과정을 안내하고 배포 단순화를 위한 Servbay의 노력을 보여줍니다. 전제 조건 머신에 Servbay가 설치되어 ...
    프로그램 작성 2024-11-08에 게시됨
  • 리캡차를 우회하는 방법
    리캡차를 우회하는 방법
    No matter how many times people wrote that the captcha has outlived itself long time ago and no longer works as effectively as its developers would ha...
    프로그램 작성 2024-11-08에 게시됨
  • super를 사용하여 슈퍼클래스 생성자 호출
    super를 사용하여 슈퍼클래스 생성자 호출
    하위 클래스는 super(parameter-list); 형식을 사용하여 상위 클래스에 의해 정의된 생성자를 호출할 수 있습니다. parameter-list는 슈퍼클래스 생성자에 필요한 매개변수를 지정해야 합니다. 하위 클래스의 생성자 내에서 실행되는 첫 번째 문은 항...
    프로그램 작성 2024-11-08에 게시됨
  • C++에서 다른 컨테이너의 반복자를 비교할 수 있습니까?
    C++에서 다른 컨테이너의 반복자를 비교할 수 있습니까?
    다른 컨테이너의 반복자 비교: 주의 사항C에서 반복자는 컬렉션 순회를 위한 강력한 메커니즘을 제공합니다. 그러나 다른 컨테이너의 반복자를 사용할 때는 제한 사항을 인식하는 것이 중요합니다.다른 컨테이너의 반복자를 비교하는 것이 합법적인지에 대한 질문이 자주 발생합니다....
    프로그램 작성 2024-11-08에 게시됨
  • FastAPI 돕기: 문서 번역에 기여하는 방법
    FastAPI 돕기: 문서 번역에 기여하는 방법
    One of the great features of FastAPI is its great documentation ?. But wouldn't it be better if more people around the world had access to this docume...
    프로그램 작성 2024-11-08에 게시됨
  • CSS와 AngularJS를 사용하여 수직 HTML 테이블을 만드는 방법은 무엇입니까?
    CSS와 AngularJS를 사용하여 수직 HTML 테이블을 만드는 방법은 무엇입니까?
    세로 HTML 테이블세로 행이 있는 HTML 테이블을 생성하면 행 머리글이 위쪽이 아닌 왼쪽이요. 이를 달성하려면 CSS 스타일을 적용하여 테이블 구조를 변환할 수 있습니다.CSS 스타일링테이블 행을 세로 열로 렌더링하려면 다음 CSS 규칙을 따르세요. 사용할 수 있습...
    프로그램 작성 2024-11-08에 게시됨
  • 커스텀 후크를 사용하여 React에서 로직 재사용: 실용 가이드
    커스텀 후크를 사용하여 React에서 로직 재사용: 실용 가이드
    사용자 정의 후크는 React 내장 후크와 달리 보다 구체적인 목적으로 사용되는 React의 강력한 기능이며, 공통 기능을 독립적인 기능으로 캡슐화하여 수행됩니다. 사용자 정의 후크는 재사용성을 촉진하고 구성 요소 구성을 개선하며 전반적으로 코드 유지 관리성을 향상시킵...
    프로그램 작성 2024-11-08에 게시됨
  • ReactJS로 무료 AI 이미지 생성기 구축
    ReactJS로 무료 AI 이미지 생성기 구축
    안녕하세요 개발자 여러분, 오늘은 ReactJS를 사용하여 이미지 생성기를 만드는 방법을 보여 드리겠습니다. Black Forest Labs와 Together AI 덕분에 모두 무료로 사용할 수 있습니다. 1단계: 프로젝트 설정 이 튜토리얼에서는 Vit...
    프로그램 작성 2024-11-08에 게시됨
  • 문자열의 연결 또는 중괄호: 성능과 미학을 최적화하는 접근 방식은 무엇입니까?
    문자열의 연결 또는 중괄호: 성능과 미학을 최적화하는 접근 방식은 무엇입니까?
    문자열의 변수 연결과 중괄호: 성능 및 미학 평가문자열 조작 영역 내에서 개발자는 종종 딜레마에 직면합니다. 문자열 내에서 변수를 연결해야 합니까, 아니면 대신 중괄호를 선택해야 합니까? 각 방법에는 고유한 장점과 단점이 있으므로 정보에 입각한 결정을 내리기 위해 자세...
    프로그램 작성 2024-11-08에 게시됨
  • 나는 Granite를 시험해 보았다.
    나는 Granite를 시험해 보았다.
    화강암 3.0 Granite 3.0은 다양한 엔터프라이즈 수준 작업을 위해 설계된 가벼운 오픈 소스 생성 언어 모델 제품군입니다. 다국어 기능, 코딩, 추론, 도구 사용을 기본적으로 지원하므로 기업 환경에 적합합니다. 이 모델을 실행하여 어떤 작업을 처...
    프로그램 작성 2024-11-08에 게시됨
  • JavaScript 기능 익히기: 개발자를 위한 종합 가이드
    JavaScript 기능 익히기: 개발자를 위한 종합 가이드
    JavaScript Functions A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "...
    프로그램 작성 2024-11-08에 게시됨
  • Go의 확률적 조기 만료
    Go의 확률적 조기 만료
    캐시 스탬피드 정보 이런 저런 것을 캐시해야 하는 상황에 자주 직면하게 됩니다. 종종 이러한 값은 일정 기간 동안 캐시됩니다. 당신은 아마도 패턴에 익숙할 것입니다. 캐시에서 값을 얻으려고 시도하고, 성공하면 이를 호출자에게 반환하고 하루를 호출합니다....
    프로그램 작성 2024-11-08에 게시됨
  • Next.js 캐싱: 효율적인 데이터 가져오기로 앱 속도 향상
    Next.js 캐싱: 효율적인 데이터 가져오기로 앱 속도 향상
    Next.js의 캐싱은 단지 시간을 절약하는 것이 아닙니다. 중복된 네트워크 요청을 줄이고, 데이터를 최신 상태로 유지하며, 앱이 최고의 성능을 발휘하도록 만드는 것입니다. 데이터를 더 오랫동안 캐시된 상태로 유지하거나 필요에 따라 새로 고치려는 경우 Next.js는...
    프로그램 작성 2024-11-08에 게시됨
  • My Go 템플릿 조건부 확인이 실패하는 이유는 무엇입니까?
    My Go 템플릿 조건부 확인이 실패하는 이유는 무엇입니까?
    Go 템플릿: 조건부 검사 문제 해결Go 템플릿 렌더링에서 구조체 필드에 대한 조건부 검사가 때때로 예상대로 작동하지 않을 수 있습니다. bool 필드 isOrientRight가 올바르게 평가되지 않는 다음 예를 고려하십시오.type Category struct { ...
    프로그램 작성 2024-11-08에 게시됨

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3