github.com/zhongdalu/gf@v1.0.0/g/container/gtype/string.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gtype
     8  
     9  import (
    10  	"sync/atomic"
    11  )
    12  
    13  type String struct {
    14  	value atomic.Value
    15  }
    16  
    17  // NewString returns a concurrent-safe object for string type,
    18  // with given initial value <value>.
    19  func NewString(value ...string) *String {
    20  	t := &String{}
    21  	if len(value) > 0 {
    22  		t.value.Store(value[0])
    23  	}
    24  	return t
    25  }
    26  
    27  // Clone clones and returns a new concurrent-safe object for string type.
    28  func (v *String) Clone() *String {
    29  	return NewString(v.Val())
    30  }
    31  
    32  // Set atomically stores <value> into t.value and returns the previous value of t.value.
    33  func (v *String) Set(value string) (old string) {
    34  	old = v.Val()
    35  	v.value.Store(value)
    36  	return
    37  }
    38  
    39  // Val atomically loads t.value.
    40  func (v *String) Val() string {
    41  	s := v.value.Load()
    42  	if s != nil {
    43  		return s.(string)
    44  	}
    45  	return ""
    46  }