← Back to Go Course | Chapter 6: Structs & Methods | Lesson 5 of 6

Constructor के Patterns

Go में कोई built-in constructor keyword नहीं है, इसलिए programmers New___ नाम का एक साधारण function लिखते हैं जिसका इकलौता काम एक उपयोग के लिए तैयार struct बनाना और सौंपना है।
Syntax
go
func NewName(param type) *Name {
    return &Name{Field: param}
}

A Basic Constructor Function

चूंकि Go में कोई constructor keyword नहीं है, idiomatic pattern एक साधारण function है, आमतौर पर NewType नाम का, जो एक struct value बनाता है (अक्सर कुछ setup logic के साथ) और इसे return करता है।

Note: किसी type X के लिए function को NewX नाम देना लगभग universal Go convention है।

उदाहरण: A Basic Constructor Function

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define a struct type named Person
type Person struct {
	Name string
	Age  int
}

// Define the function NewPerson
func NewPerson(name string, age int) Person {
	// Send Person{Name: name, Age: age} back to the caller
	return Person{Name: name, Age: age}
}

// main is where the program starts running
func main() {
	// Short declaration: create p and infer the type
	p := NewPerson("Divya", 27)
	// Print the values followed by a newline
	fmt.Println(p)
}

Validating Input in a Constructor

एक constructor function arguments validate करने और अगर वे invalid हों तो एक error return करने की एक स्वाभाविक जगह है, bad data को शुरू में ही struct बनाने से रोकते हुए।

उदाहरण: Validating Input in a Constructor

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"errors"
	"fmt"
)

// Define a struct type named Account
type Account struct {
	Balance float64
}

// Define the function NewAccount
func NewAccount(initial float64) (*Account, error) {
	// Check whether initial < 0
	if initial < 0 {
		return nil, errors.New("initial balance cannot be negative")
	}
	return &Account{Balance: initial}, nil
}

// main is where the program starts running
func main() {
	// Short declaration: create acc, err and infer the type
	acc, err := NewAccount(100)
	// Print the values followed by a newline
	fmt.Println(acc, err)
}

Returning a Pointer from a Constructor

जब किसी type में pointer-receiver methods हों, इसके constructor का सीधे एक *Type return करना आम है, ताकि value बिना अतिरिक्त addressing के उन methods के ज़रिए तुरंत mutate होने के लिए तैयार हो।

उदाहरण: Returning a Pointer from a Constructor

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// Define a struct type named Counter
type Counter struct {
	value int
}

// Define the function NewCounter
func NewCounter() *Counter {
	// Send &Counter{value: 0} back to the caller
	return &Counter{value: 0}
}

// Define the method Increment on type Counter
func (c *Counter) Increment() {
	c.value++
}

// main is where the program starts running
func main() {
	// Short declaration: create c and infer the type
	c := NewCounter()
	c.Increment()
	c.Increment()
	fmt.Println(c.value)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. दूसरी languages जैसी एक special constructor syntax की उम्मीद करना -- Go बस ordinary functions उपयोग करता है, conventionally NewXxx नाम वाले।
  2. सभी struct fields export करना जब एक constructor का मकसद invariants enforce करना हो, callers को सीधे fields सेट करके validation bypass करने देते हुए।
  3. किसी NewXxx function से एक struct value return करना जब एक pointer intended था, type के दूसरे pointer-receiver methods के साथ inconsistency का कारण बनते हुए।
चैप्टर सारांश
  • Go में कोई dedicated constructor syntax नहीं है -- conventionally NewType नाम वाला एक साधारण function एक value बनाता और return करता है।
  • Constructor functions return करने से पहले inputs validate और sensible defaults सेट कर सकते हैं।
  • किसी constructor से एक pointer (*Type) return करना आम है जब type में pointer-receiver methods हों।
  • एक constructor function के साथ unexported fields यह enforce करते हैं कि objects सिर्फ valid initial states के ज़रिए बनाए जाएं।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.